Angular 2 - 如何为动态加载的组件设置 id 属性

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

本文关键字:组件 设置 id 属性 加载 动态 Angular      更新时间:2023-09-26

我正在使用DynamicComponentLoader来加载子组件,它会产生以下html:

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

这是我如何在父级中加载组件的方式

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

如何将 id 属性添加到子组件,以便它生成以下 html:

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

可能的话,我会添加一个字段ChildComponent并将id绑定到它:

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

另请参阅 http://plnkr.co/edit/ihb7dzRlz1DO5piUvoXw?p=preview#

一种更笨拙的方式是

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

与其直接访问nativeElement属性,不如对Renderer执行相同的操作。