Angular 4 - 在容器

时间:2018-03-08 14:25:10

标签: angular

我想创建动态组件并在运行时插入其他组件。

我用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 ......

1 个答案:

答案 0 :(得分:1)

只需为实例分配道具

尝试使用逻辑输入

  addComponent() {
        const componentFactory = 
         this.componentFactoryResolver.resolveComponentFactory(MyComponent);
        const component = this.container.createComponent(componentFactory);
      component.myVariable = blabla
    }

并把this.buildSomething(this.variable);在ngOnChange。