In most cases, BeetleJuice's answer is the right decision: to use the functionality of several components in services .
However, sometimes you have uniquely connected components that you want to include in the HTML template of the parent component.
In this case, the use of the service will be overhead. Fortunately, you can use template reference variables (#var)
Let's say you have a popup component:
// import... @Component({ selector: 'my-popup', template: '<div *ngIf="visible"><ng-content></ng-content></div>' }) export class MyPopupComponent { public visible: boolean = false; public toggle() { this.visible = !this.visible; } }
And a switching component that can trigger a popup component:
// import... @Component({ selector: 'my-popup-toggle', template: '<button (click)="popup?.toggle()"><ng-content></ng-content></button>' }) export class MyPopupToggleComponent { @Input('for') popup: MyPopupComponent; }
Then it is so easy to connect components through HTML:
<div> <my-popup #popup1>Good popup</my-popup> <my-popup #popup2>Better popup</my-popup> <my-popup #popup3>Best popup</my-popup> </div> <div> <my-popup-toggle [for]="popup1">Toggle the good</my-popup-toggle> <my-popup-toggle [for]="popup2">Toggle the better</my-popup-toggle> <my-popup-toggle [for]="popup3">Toggle the best</my-popup-toggle> <my-popup-toggle [for]="popup3">Toggle the best with another button</my-popup-toggle> </div>
In very simple situations, you can do something like this:
<div> <my-popup #popup4>Best popup II</my-popup> </div> <div> <button (click)="popup4.show()">Toggle the best II</button> </div>
If necessary, you can also access the template reference variable from the parent component:
// import... @Component({ selector: 'my-parent-comonent', template: ' ...<my-popup #popup5>Best popup III</my-popup>... ...<my-popup #popup6>Best popup IV</my-popup>... ' }) export class MyParentComponent { @ViewChild('popup5') popup5: MyPopupComponent; @ViewChild('popup5') popup5: MyPopupComponent; showPopup5() { this.popup5.show(); } showPopup6() { this.popup6.show(); } }