简体   繁体   English

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

[英]How to pass data when changing views using ng-template

I have a component that has a dynamic view, which I am implementing using an ng-template . 我有一个具有动态视图的组件,正在使用ng-template The following is that component, lets say parent.component.ts . 以下是该组件,可以说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);
    }
}

The child.component.ts is written like this: child.component.ts的编写如下:

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

I want to call the loadComponent method like this: 我想这样调用loadComponent方法:

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

How can I pass the options object into the child component, so that the title gets the value 'Main File'? 如何将options对象传递到子组件中,以便标题获得值“ Main File”?

componentRef has the attribute instance which is the actual instance of the created component. componentRef具有属性instance ,它是所创建组件的实际实例。 From this instance, you can access to all public attributes and functions of the component. 在此实例中,您可以访问组件的所有公共属性和功能。

You can map your options inside a function on the component or just set them from loadComponent . 您可以将选项映射到组件上的函数内,也可以仅从loadComponent设置。

Check the class doc: https://angular.io/api/core/ComponentRef#instance 检查类文档: https : //angular.io/api/core/ComponentRef#instance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM