angular input and output code example
Example 1: angular @Output()
// Parent Component
import { Component } from '@angular/core'
@Component({
selector: app-component,
template:
`
<app-item-output (newItemEvent)='addItem($event)'> </app-item-output>
<ul>
<li *ngFor='let item of items'>{{item}}</li>
</ul>
`
})
export class AppComponent {
items = ['item1', 'item2', 'item3'];
addItem(newItem: string){
this.items.push(newItem);
}
}
// Child Component
import { Output, EventEmitter } from '@angular/core';
@Component({
selector: app-item-output,
template:
`
<label>Add an item: <input #newItem></label>
<button (click)='addNewItem(newItem.value)'>Add to parent's list</button>
`
})
export class ItemOutputComponent {
@Output() newItemEvent = new EventEmitter<string>();
addNewItem(value: string) {
// this method emits the value of newItemEvent
this.newItemEvent.emit(value);
}
}
Example 2: send event to child component angular
Parent-Component
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
Parent-HTML
<child [events]="eventsSubject.asObservable()"> </child>
Child-Component
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
Example 3: output event angular
@Component({...})
export class CounterComponent {
@Input()
count: number = 0;
@Output()
change: EventEmitter<number> = new EventEmitter<number>();
increment() {
this.count++;
this.change.emit(this.count);
}
decrement() {
this.count--;
this.change.emit(this.count);
}
// in parent component
//(change)="countChange($event)">
}