Parent and child components
// If the nested component wants to receive input from it's container, it must expose a property to that container
// and it can do that using @Input() decorator
// StarComponent is the nested component here
@Component({
selector: 'pm-star'
})
export class StarComponent {
@Input() rating: number;
}
// In parent container html, pass in 'product.starRating' (parent container's property)
// to the nested component's property (rating' property of StarComponent)
<td>
<pm-star [rating]='product.starRating'></pm-star>
</td>
// if the nested component wants to send information back to it's container
// it can raise an event and pass a payload to the container.
// In this example payload is string
// Nested component exposes an event using @Output() decorator
export class StarComponent {
// we can declare multiple @Output() properties (with different names) to pass multiple pieces of information
@Output() notify: EventEmitter<string> = new EventEmitter<string>();
onClick() {
this.notify.emit('Clicked!');
}
}
// start.component.html
<div (click)="onClick()"> click here </div>
// container.component.html
// $event = 'Clicked!' (the message passed from the nested component)
<td>
<pm-star [rating]='product.starRating'
(notify)="onNotify($event)"></pm-star>
</td>
export Class ContainerComponent {
onNotify(message: string): void {
// do something with the 'Clicked!' message received from the star component
}
}