Communication
Using @Input
and @Output
¶
In this approach, the child component, which is embedded in the parent component, has both @Input
and @Output
properties which can be referenced in the html selector.
-
Type into the parent input
- Value is updated in the child component
-
Type into the child input
- Value is emitted to the parent when submitted
View the full demo on StackBlitz
Using a Service
¶
Components can communicate with any number of other components with the use of a Service
that can be injected into each component. In the following example we have a parent component with a son and daughter component. The son or daughter component can emit values that all other components listen to and print.
<fieldset>
<legend>
<h1>Brother Component</h1>
</legend>
<p>Message to send to anybody</p>
<input type="text" [(ngModel)]="inputText" (keyup.enter)="onClick()" />
<button (click)="onClick()">Submit</button>
<div *ngIf="sisterMessage$ | async as sisterMessage">
<p>Sister said: {{ sisterMessage }}</p>
</div>
</fieldset>
@Injectable()
export class UiService {
private brotherMessage = new Subject<string>();
public brotherMessage$ = this.brotherMessage.asObservable();
private sisterMessage = new Subject<string>();
public sisterMessage$ = this.sisterMessage.asObservable();
constructor() {}
brotherSpeak(message: string): void {
this.brotherMessage.next(message);
}
sisterSpeak(message: string): void {
this.sisterMessage.next(message);
}
}
View the full demo on StackBlitz
Template selector reference¶
The instance of the child selector can be used throughout the parent template.
- Parent component displays the message property of the child component
View the full demo on StackBlitz
Using @ViewChild
¶
By injecting the child component programatically, all of it's public methods can be accessed within the parent component.
View the full demo on StackBlitz