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

Ees*_*esa 7 javascript angular

DynamicComponentLoader用来加载子组件,它产生以下html:

<child-component> Child content here </child-component>
Run Code Online (Sandbox Code Playgroud)

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

ngAfterViewInit(){
        this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child');
  }
Run Code Online (Sandbox Code Playgroud)

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

<child-component id="someId" > Child content here </child-component>
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 10

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

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

另见http://plnkr.co/edit/ihb7dzRlz1DO5piUvoXw?p=preview#

一种更黑客的方式

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

而不是nativeElement直接访问属性,应该可以做同样的事情Renderer.

  • 仅供参考,我的TSLint建议在主机组件参数上使用`@ HostBinding`,这个语法对我来说就像是@HostBinding('attr.id')id;`这就像`@ Input`参数一样在组件内 (4认同)