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

时间:2016-02-29 15:32:14

标签: javascript angular

我正在使用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>

1 个答案:

答案 0 :(得分:10)

如果可能,我会向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');
this.dcl.loadIntoLocation(Dynamic, this.ref, 'child').then((cmp) => {
  cmp.location.nativeElement.id = 'someId';
});

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

更黑客的方式是

nativeElement

不应直接访问Renderer属性,而应该可以对var casper = require('casper').create({ verbose: true, logLevel: "info", viewportSize: {width: 1280,height: 720}, pageSettings: {userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"} }); casper.start('http://www.hotmail.com').then(function () { console.log('got here'); }); casper.wait(500, function () { console.log('wait'); }); casper.then(function(){ this.sendKeys("[name='loginfmt']", 'peterwhite12345678@outlook.com'); this.sendKeys("[name='passwd']", '12345678peterwhite'); this.click("[type='submit']"); console.log('entering log in information'); }); casper.wait(5000, function () { console.log('wait'); }); casper.then(function (){ console.log('printscreen'); casper.capture('there_is_nothing_by_the_right_side.png') }); casper.run(); 执行相同操作。