【发布时间】:2018-08-16 22:40:49
【问题描述】:
我想创建一个动态组件并在运行时插入其他组件。
我用ViewContainerRef解决了这个问题:
import { MyComponent } from "./component-path";
@Component({
template: `<ng-template #container></ng-template>`
})
export class GeneralDataComponent implements OnInit {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit() {
this.addComponent();
}
addComponent() {
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(MyComponent);
const component = this.container.createComponent(componentFactory);
}
}
我的组件类:
@Component({
selector: "s-my-component",
template: require("./mycomponent.html")
})
export class MyComponent implements OnInit {
constructor(private myVariable: String) { }
ngOnInit() {
this.buildSomething(this.variable);
}
buildSomething(variable : string) {
//some logic here
}
}
效果很好,MyComponent 被放置在容器中,但我需要为 myVariable 设置值才能让他正常工作。
我该怎么做?
我不想为myVariable 逻辑的任何可能值创建大量组件。
还有另一种使用 Angular 4 动态插入组件的方法,还是有更好的方法来使用 @ViewChild?我是 Angular 的新手,有什么建议......
【问题讨论】:
标签: angular