Updated on Kisan Patel
How to inject a component instance into a child directive or component in Angular?
Follow below example to inject a component instance into a child directive or component:
count.component.ts
import { Component } from "@angular/core"; @Component({ template: ` Count: {{ count }} <ng-content></ng-content> `, selector: "count-component" }) export class CountComponent { count: number = 0; }
app.component.ts
import { Component, VERSION } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html" }) export class AppComponent {}
app.component.html
<count-component> <button increment>Increment</button> </count-component>
increment.directive.ts
import { Directive, HostListener } from "@angular/core"; import { CountComponent } from "./count.component"; @Directive({ selector: "[increment]" }) export class IncrementDirective { constructor(private countComponent: CountComponent) {} @HostListener("click") increment() { this.countComponent.count += 1; } }
Demo: