Nested Component
In this entry, pass parameter from parent to child, delete event from child to parent
Input and Output Decolator
@Input
Attached to a property of any type
Prefix with @ suffix with ()
@Ouput
Attached to a property declared as an EventEmitter
Use the generic argument to define the event payload type
Use the new keyword to create an instance of the EventEmitter
Prefix with @; suffix with ()
Example
Pass rank parameter from parent, Pass event result from child
app.component.html
Parent HTML
<div> App Component <app-child =5 (notify)='onNotify($event)'></app-child> </div>
app-child is child component. rank is attr, notify is event
notifiy is event attr
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'testapp'; onNotify(message: string) { console.log(message); } }
databind/child.component.html
<p>child works!</p> <button (click)="clickbutton()">Click Child!</button>
This is child component HTML. Has button and event is clickbutton method
databind/child.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() rank: number = 1; @Output() notify: EventEmitter<string> = new EventEmitter<string>(); constructor() { } ngOnInit(): void { } clickbutton() { console.log('rank:' + this.rank); this.notify.emit('clicked!'); } }
notify is output emitter delegate event to parent
rank is attr used when the parent use this component
コメント