最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 - How to set id attribute to the dynamically loaded component - Stack Overflow

programmeradmin1浏览0评论

I am using DynamicComponentLoader to load the child component and it produces the following html:

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

and here is how I am loading the component in the parent

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

How can I add the id attribute to the child component so that it produces the following html:

<child-component id="someId" > Child content here </child-component>

I am using DynamicComponentLoader to load the child component and it produces the following html:

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

and here is how I am loading the component in the parent

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

How can I add the id attribute to the child component so that it produces the following html:

<child-component id="someId" > Child content here </child-component>
Share Improve this question asked Feb 29, 2016 at 15:32 EesaEesa 2,8592 gold badges37 silver badges53 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 15

If possible I would add a field to ChildComponent and bind 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 hacky way would be

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

Instead of accessing nativeElement properties directly it should be possible to do the same with Renderer.

发布评论

评论列表(0)

  1. 暂无评论