Angular 4 access template element without local template variable

I have a parent component (say ParentComponent), and I need to add a lot of child components (for example ChildComponent1, ChildComponent2... ChildComponentN) to it dynamically . Each component is different.

I followed this to solve my problem: Angular 2 RC5-6 - insert component dynamically

But in order to access the template element (simple <div>) that will be mine ChildComponentthrough @ViewChild, I need to set a local template variable in this element <div>.

However, in my case, I cannot do this because I cannot set a local template variable with a dynamic name. Therefore, my element is <div>characterized only by a unique id attribute, which is added dynamically (for example, <div id="child1">).

Is there a way to access an element <div>through component implementation in typescript without a local template variable?

+4
source share
2 answers

I think you can create a directive mydirthat will output the element:

@Directive({selector: 'mydir'})
export class MyDir {
  @Input('mydir') id;
  constructor(public vc: ViewContainerRef) {

  }
}

and then apply it to the div:

<div [mydir]="child1">
<div [mydir]="child2">

and then request it from the parent component:

@ViewChildren(MyDir) children;

ngAfterViewInit() {
   const specificID = 'child1';
   const instance = children.find((c)=>{c.id === specificID});
   const vc = instance.vc;
}
+2
source

angular 4, * ngComponentOutlet = "dinamicCompomponent"

0

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


All Articles