Dartz
Dartz

Reputation: 165

Angular 4 access template element without template local variable

I have a parent component (say ParentComponent) and I need to add many children components (say ChildComponent1, ChildComponent2, ... ChildComponentN) to it dynamically. Each component is different.

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

But in order to access the template element (a simple <div>) that will hold my ChildComponents through @ViewChild, I need to set a template local variable on this <div> element.

However, in my case, I can't do that because I can't set a template local variable with a dynamically name. So my <div> element is only characterized by an unique id attribute that is added dynamically (like <div id="child1">).

Is there any way to access my <div> element through the component implementation in typescript without template local variable ?

Upvotes: 4

Views: 1478

Answers (2)

Max Koretskyi
Max Koretskyi

Reputation: 105563

I think you can create a directive mydir that will expose an 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 query it from the parent component:

@ViewChildren(MyDir) children;

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

Upvotes: 2

alehn96
alehn96

Reputation: 1393

If you have angular 4 you can use *ngComponentOutlet="dinamicCompomponent" for insert component dinamically

Upvotes: 0

Related Questions