【发布时间】:2016-12-16 02:33:30
【问题描述】:
我一直在试验 Angular 2,我已经能够通过获取现有子级的 @ViewChild 然后使用 ComponentResolver 添加我的动态组件来动态地将一个组件添加到另一个子级。
但是,如果您无法控制模板(即您正在动态地将组件添加到指令的子级),您应该怎么做?我不知道我的指令将在容器中包含哪些元素,那么我如何获得类似的 ViewContainerRef 呢?
编辑: 我似乎在获取指令的 @ViewChild 时也遇到了问题。 Here's 我在我的应用程序中发生的事情..
Hello.component.ts
import { Component } from '@angular/core'
@Component({
selector: 'hello',
template: '<h1>Hi!</h1>',
styles: ['h1{background-color: green}']
})
export class HelloComponent {}
Test.directive.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);
});
}
}
app.component.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 {
}
【问题讨论】:
标签: angular