【问题标题】:Angular 2 shared component with component as attributesAngular 2以组件为属性的共享组件
【发布时间】:2018-03-01 15:16:34
【问题描述】:

我有一个共享组件,它可以显示一个切换按钮,这个切换按钮可以让你在两个子组件之间切换,这两个组件必须作为调用 SharedComponent 的父级的输入传递。 请问有什么想法吗?

【问题讨论】:

    标签: angular input components shared viewchild


    【解决方案1】:

    我认为 ngComponentOutlet 就是您要查找的内容: https://angular.io/api/common/NgComponentOutlet

    然后你可以这样做:

    <a (click)="doSwitch()">Switch</a>
    <ng-container *ngComponentOutlet="component1"></ng-container>
    <ng-container *ngComponentOutlet="component2"></ng-container>
    

    在打字稿中:

    Input()
    component1: Type<any>;
    
    Input()
    component2: Type<any>;
    
    ...
    

    使用组件时:

    <switch-component [component1]="comp1" [component2]="comp2"></switch-component>
    
    comp1: Type = ParentComponent1;
    comp2: Type = ParentComponent2;
    

    【讨论】:

    • 谢谢 Franziskus,但是如何将组件和属性作为参数传递。
    • 我添加了一些关于如何使用该组件的代码。我不知道是否可以将参数绑定到 NgComponent 内部的组件。也许您不应该在这些组件中使用输入。也许在这里使用服务或事件会更好。
    猜你喜欢
    • 2017-06-12
    • 2017-07-30
    • 2017-01-04
    • 2017-04-15
    • 2017-12-31
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多