Angular 2 - How to set the id attribute of a dynamically loaded component

I use DynamicComponentLoader to load the child component and it creates the following html:

 <child-component> Child content here </child-component> 

and this is how I load the component into the parent

 ngAfterViewInit(){ this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child'); } 

How to add id attribute to child component so that it creates the following html:

 <child-component id="someId" > Child content here </child-component> 
+6
source share
1 answer

If possible, I would add the field to ChildComponent and ChildComponent id to it:

 @Component({ selector: 'child-component', host: {'[id]': 'id'} }) class ChildComonent { id:string; } 
 this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child') .then(cmp => cmp.instance.id = 'someId'); 

See also http://plnkr.co/edit/ihb7dzRlz1DO5piUvoXw?p=preview#

A more hacker way would be

 this.dcl.loadIntoLocation(Dynamic, this.ref, 'child').then((cmp) => { cmp.location.nativeElement.id = 'someId'; }); 

Instead of directly accessing nativeElement properties, nativeElement should do the same with Renderer .

+8
source

All Articles