如何使用ng-template更改视图时传递数据

时间:2018-04-05 11:53:15

标签: javascript angular

我有一个具有动态视图的组件,我使用ng-template实现。 以下是该组件,比如parent.component.ts

@Component({
    ...
    template: '<div><ng-template child-area></ng-template></div>',
    ...
})

export class ParentComponent implements OnInit {

    @ViewChild(ChildAreaDirective) childArea: ChildAreaDirective;

    loadComponent (details) {
        let _vcf = this.childArea.viewContainerRef;
        let _cf= resolveComponentFactory(childrenList[details.name]);

        // How do I pass the options object from here into the child component??
        this.childOptions = details.options;

        let componentRef = _vcf.createComponent(_cf);
    }
}

child.component.ts的写法如下:

@Component ({
    template: '<div>{{ title }}</div>'
})

我想像这样调用loadComponent方法:

parent.loadComponent({ name: 'choose-doc', options: {title: "Main File"} });

如何将options对象传递给子组件,以便标题获得值&#39;主文件&#39;?

1 个答案:

答案 0 :(得分:0)

componentRef具有属性instance,它是创建的组件的实际实例。在此实例中,您可以访问组件的所有公共属性和功能。

您可以在组件的函数内映射选项,或者只从loadComponent设置它们。

检查课程文档:https://angular.io/api/core/ComponentRef#instance