learn angular - event
- child to parent comunication with event using @Output
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
styles: `.btn { padding: 5px; }`,
template: `
<button class="btn" (click)="addItem()">Add Item</button>
`,
standalone: true,
})
export class ChildComponent {
@Output() addItemEvent = new EventEmitter<string>();
addItem() {
this.addItemEvent.emit('🐢');
}
}
‘🐢’ is emited by child component
import {Component} from '@angular/core';
import {ChildComponent} from './child.component';
@Component({
selector: 'app-root',
template: `
<app-child (addItemEvent)="addItem($event)" />
<p>🐢 all the way down </p>
`,
standalone: true,
imports: [ChildComponent],
})
export class AppComponent {
items = new Array();
addItem(item: string) {
this.items.push(item);
}
}
‘🐢’ is emitted in child and become the $event
.