Events may be displayed for dynamically generated components

What am I trying to do:

  • Creating components dynamically (done)
  • Allow dynamically created components to use "outputs" so that parent components can listen for changes from children.

Here is Plnkr for what I'm trying to do. Plnker → https://plnkr.co/edit/XpDCGIwd2at9oR74lpY5?p=preview

When the user clicks "+ Component", the next component is created

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
let ref = this.container.createComponent(componentFactory);

Inside each child component that is added when the user clicks the "Fire Event"

<span class="initiateParentAction" 
  (click)="fireEventEmitter()" [class.eventFired]="eventFired==true">Fire Output Event: {{eventFired}}</span>

he calls the following

fireEventEmitter(){
    console.log("Event Fired");
    this.parentActionReq.emit({
      action: "helloWorld"
    });
    this.eventFired = true;
    setTimeout(() => this.eventFired=false, 2000);
}

The parent component (in this case, the "App" component) listens for this output, as shown here.

<ng-container #container 
    (parentActionReq)="childActionInitiated($event)"></ng-container>

, . Plnker " " .

, - , , - OnInit. .

, , .

Observables, , , Output .

.

+4
1

, . , .

ref.instance.someProp = 'someVal';
ref.instance.someOutput.subscribe(val => this.prop = val);

. Angular 2 ,

+4

Source: https://habr.com/ru/post/1656819/


All Articles