Skip to content Skip to sidebar Skip to footer

What Is The Correct Way To Call A Method Of The Host Or Parent Component From A Dynamically Added Component?

I want to know the correct way to call the greet() method declared in the host component from a dynamically added component src/app/app.component.ts import { Component, ViewChi

Solution 1:

You can add an output() in OneComponent then you subscribe in your AppComponent like below:

import { Component, OnInit, Output, EventEmitter } from'@angular/core';

@Component({
  selector: 'app-one',
  templateUrl: './one.component.html',
  styleUrls: ['./one.component.css'],
})
exportclassOneComponentimplementsOnInit {
  
  @Output()
  greetEvent: EventEmitter<void> = newEventEmitter<void>();

  constructor() {}

  ngOnInit(): void {}

  onClick(): void {
    // how to call host component greet method?this.greetEvent.emit();
  }
}

src/app/app.component.ts

import {
  Component,
  ViewChild,
  ComponentFactoryResolver,
  ViewContainerRef,
} from'@angular/core';

import { OneComponent } from'./application/one/one.component';
import { TwoComponent } from'./application/two/two.component';
import { ThreeComponent } from'./application/three/three.component';
import { AdHostDirective } from'./ad-host.directive';

enumTarget {
  ONE = 'one',
  TWO = 'two',
  THREE = 'three',
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
exportclassAppComponent {
  @ViewChild(AdHostDirective, { static: true }) adHost: AdHostDirective;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  toggle(target: string): void {
    letcomponentFactory: any;

    switch (target) {
      caseTarget.ONE:
        componentFactory = this.componentFactoryResolver.resolveComponentFactory(
          OneComponent
        );
        break;
      caseTarget.TWO:
        componentFactory = this.componentFactoryResolver.resolveComponentFactory(
          TwoComponent
        );
        break;
      caseTarget.THREE:
        componentFactory = this.componentFactoryResolver.resolveComponentFactory(
          ThreeComponent
        );
        break;
      default:
        break;
    }

    const viewContainerRef = this.adHost.viewContainerRef;

    viewContainerRef.clear();
    constcomponentRef: ComponentRef<any> = viewContainerRef.createComponent(componentFactory);
    componentRef.instance.greetEvent.subscribe(() =>this.greet());
  }

  greet(): void {
    alert('Hi');
  }
}

Post a Comment for "What Is The Correct Way To Call A Method Of The Host Or Parent Component From A Dynamically Added Component?"