我想创建动态组件并在运行时插入其他组件。
我用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的新手,任何sugestions ......
答案 0 :(得分:1)
只需为实例分配道具
尝试使用逻辑输入
addComponent() {
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(MyComponent);
const component = this.container.createComponent(componentFactory);
component.myVariable = blabla
}
并把this.buildSomething(this.variable);在ngOnChange。