【问题标题】:Dynamic Injection in Angular, injecting a component to parent componentAngular中的动态注入,将组件注入父组件
【发布时间】:2018-11-02 02:24:30
【问题描述】:

如何在 Angular 4 中动态地将一个组件注入另一个组件,以及如何将值从父组件传递给子组件。任何人都可以帮助提供示例工作代码。

【问题讨论】:

    标签: angular


    【解决方案1】:

    这个问题有点不清楚,肯定会因为缺少任何示例代码来说明您尝试过的事情,以及缺少关于您要完成的工作的详细信息。

    基本上,一个组件可以包含在另一个组件中,使用选择器作为 HTML 元素,如下所示:

    在父组件中:

    <div>
       <ai-star [rating]='product.starRating'
                (ratingClicked)='onRatingClicked($event)'>
       </ai-star>
    </div>
    

    子组件:

    @Component({
        selector: 'ai-star',
        templateUrl: 'app/shared/star.component.html',
        styleUrls: ['app/shared/star.component.css']
    })
    export class StarComponent implements OnChanges { ... }
    

    您可以在这里找到完整的示例代码:https://github.com/DeborahK/Angular2-GettingStarted

    【讨论】:

      【解决方案2】:

      组件的动态注入请看代码here我们要使用ComponentFactoryResolver

      let adItem = this.user;
          let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
          let viewContainerRef = this.injectHost.viewContainerRef;
          viewContainerRef.clear();
          let componentRef = viewContainerRef.createComponent(componentFactory);
          (<InjectComponent>componentRef.instance).data = adItem.data;
      

      【讨论】:

        猜你喜欢
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        • 2016-06-10
        • 2016-04-05
        相关资源
        最近更新 更多