Angular Components (WIP)
- Sharing data between directives and components
- Trigger a method in another component
-
Emit event to sending data back from component
@output
- Add an event listener to the component's selector
- Additional Resources
@ViewChild(ComponentType) propertyName!: ComponentType;
Sharing data between directives and components
You can share data between components using Angular's @Input()
and @Output()
decorators.
@Input()
lets a parent component update data in the child component. Conversely, @Output()
lets the child send data to a parent component.
Sending data from the HTML
<!-- pass primitive value -->
<app-child dataFromParent="some value"/>
<!-- bind to a value -->
<app-child [dataFromParent]="parentValue"/>
<!-- pass nested items -->
<app-child [dataFromParent]="object.item"/>
Fetching data with @Input()
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
template: '<p>{{ dataFromParent }}</p>'
})
export class ChildComponent {
@Input() dataFromParent: string;
constructor() {
// You can use this.dataFromParent here for initialization
console.log(this.dataFromParent);
}
}
Trigger a method in another component
From the parent component, get a reference to the child component using @ViewChild()
. Then call the method in the child component.
@ViewChild()
is a decorator that takes the component class as an argument.
ChildComponent
is the class of the child component.
child
is the name of the property that will hold the reference to the child component.
ChildComponent
is the type of the property.
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: '<app-child></app-child>'
})
export class ParentComponent {
// Get a reference to the child component
@ViewChild(ChildComponent) child: ChildComponent;
// Call this method to trigger the method in the child component
triggerMethod() {
this.child.triggerMethod();
}
}
Add a method to the child component that you want to trigger.
triggerMethod() {
console.log('Method triggered');
}
Add a button to the parent component's template that calls the triggerMethod()
method.
<button (click)="triggerMethod()">Trigger method</button>
@output
Emit event to sending data back from component @Output() newItemEvent = new EventEmitter
The component uses the @Output()
property to raise an event to notify the parent of the change.
To raise an event, an @Output()
must have the type of EventEmitter.
import { Output, EventEmitter } from '@angular/core';
@Output() newItemEvent = new EventEmitter<string>();
addNewItem(value: string) {
this.newItemEvent.emit(value);
}
Add an event listener to the component's selector
(newItemEvent)
is the event being emitted
addItem($event)
is the method in the parent component (receiver of the event)
<nk-some-component (newItemEvent)="addItem($event)" />