【发布时间】:2017-10-20 19:45:32
【问题描述】:
我正在创建一个组件并注入它。是否有一个对#theBody 的静态引用而不是让它从数组或变量中绑定?
import {ComponentRef, Injectable, Component, Injector, ViewContainerRef, ViewChild,ComponentResolver} from '@angular/core';
import { HeroListComponent } from './hero-list.component';
如果我预定义的 #theBody 比我能够创建的要好
@Component({
selector: 'my-app',
template: `<button (click)="addCmp()" >add</button>
<hero-list></hero-list>
<div #theBody ></div>
`,
directives: [HeroListComponent]
})
但我想注入,这样我就可以动态绑定组件创建。所以像这样的
@Component({
selector: 'my-app',
template: `<button (click)="addCmp()" >add</button>
<hero-list></hero-list>
<div {{customtag}} ></div>
`,
directives: [HeroListComponent]
})
我在 customtag 中定义#theBody。
export class AppComponent {
@ViewChild('theBody', {read: ViewContainerRef}) theBody;
cmp:ComponentRef;
customtag = '#theBody'
constructor(injector: Injector,private resolver: ComponentResolver) {
}
addCmp(){
console.log('adding');
this.resolver.resolveComponent(HeroListComponent).then((factory:ComponentFactory<any>) => {
this.cmp = this.theBody.createComponent(factory);
this.cmp.instance.test = "the test";
});
}
}
Plunker:https://plnkr.co/edit/RuwvwBOMK2IOXrhBQNPe?p=preview
【问题讨论】:
标签: angular data-binding components