【问题标题】:Angular 4 - insert a instantiated component dynamically in containerAngular 4 - 在容器中动态插入实例化组件
【发布时间】: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


    【解决方案1】:

    例如只分配 prop

    尝试将输入用于逻辑

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

    然后把 this.buildSomething(this.variable);在 ngOnChange 中。

    【讨论】:

    • 仍然没有找到如何通过依赖关系动态创建组件
    猜你喜欢
    • 2017-10-26
    • 2019-04-13
    • 2018-03-26
    • 2017-05-29
    • 2020-03-08
    • 1970-01-01
    • 2019-11-11
    • 2018-12-07
    • 1970-01-01
    相关资源
    最近更新 更多