我一直在尝试 Angular 2,并且我已经能够通过获取现有子组件的 @ViewChild 然后使用 ComponentResolver 添加我的动态组件来动态地将一个组件添加到另一个组件的子组件中。
但是,如果您无法控制模板(即您动态地将组件添加到指令的子项),您应该怎么做?我不知道我的指令的容器中会包含哪些元素,那么我如何获得类似的 ViewContainerRef 呢?
EDIT:我似乎在获取指令的 @ViewChild 时也遇到问题。Here's http://plnkr.co/edit/Y9dKWI8MJgnZENUWxHuX?p=preview我的应用程序中发生的事情的一个笨蛋..
你好.组件.ts
import { Component } from '@angular/core'
@Component({
selector: 'hello',
template: '<h1>Hi!</h1>',
styles: ['h1{background-color: green}']
})
export class HelloComponent {}
测试指令.ts
import { Directive, ViewChild, ViewContainerRef, ComponentResolver, OnInit } from '@angular/core';
import { HelloComponent } from './hello.component'
@Directive({
selector: '[testDir]'
})
export class TestDirective implements OnInit {
@ViewChild('div', {read: ViewContainerRef}) div;
constructor(private viewContainerRef: ViewContainerRef, private componentResolver: ComponentResolver) {}
ngOnInit() {
this.componentResolver.resolveComponent(HelloComponent).then((factory) => {
this.div.createComponent(factory);
this.viewContainerRef.createComponent(factory);
});
}
}
应用程序组件.ts
import { Component } from '@angular/core';
import { TestDirective } from './app.directive';
import { HelloComponent } from './hello.component'
@Component({
selector: 'my-app',
template: `
<div testDir>
<div #div></div>
</div>
`,
directives: [TestDirective, HelloComponent]
})
export class AppComponent {
}