【问题标题】:Loading component inside another component using @input in angular使用角度的@input将组件加载到另一个组件中
【发布时间】:2017-09-23 11:23:47
【问题描述】:

这是一个 Angular 4.x 问题。

我有一个在应用程序中随处使用的标题组件。我希望能够将另一个组件传递给它,以便它可以渲染它。我希望它像这样简单:

<app-header
    [Component]  = "myComponent"
></app-header>

这个 myComponent 可以属于正在加载标头的模块。 许多开发人员使用了不同的方法(其中一些在较新版本的 Angular 4.4.3 中已弃用)。我正在尝试以最简单和最干净的方式来做到这一点。由于我的模块是懒惰地加载,我不能将它们作为“entryComponents”放在根模块中,这对我来说很难。

我已经尝试过 NgComponentOutlet (https://angular.io/api/common/NgComponentOutlet),但它不适合我。

我也尝试过动态组件加载 (DML) (https://angular.io/guide/dynamic-component-loader),但这也不起作用。它需要我在根模块的“entryComponents”中添加动态组件。

有什么帮助吗?

【问题讨论】:

  • 您的myCompanent 有一个选择器,例如:app-my-component

标签: angular


【解决方案1】:

如果有人正在寻找我使用的解决方案,如下所示:

@Component({
    selector       : 'app-header',
    templateUrl    : `<ng-container *ngComponentOutlet="dynamicComponent"></ng-container>`,
})
export class HeaderDesktopComponent implements OnInit, OnChanges {
    @Input() component: any     = null;

    dynamicComponent = null;

    ngOnInit() {
        if ( component ) {
            this.dynamicComponent = this.component;
        }
    }
}

然后在另一个模块的模板中:

<app-header [component]="myComponent"></app-header>

在代码中:

ngOnInit() {
    this.myComponent = MyCustomHeaderComponent;
}

关键是在其所属模块的'entryComponents'中声明MyCustomHeaderComponent

更新: 还找到了一个很好的包来处理带有@Input 和@Output 的动态组件:https://www.npmjs.com/package/ng-dynamic-component

【讨论】:

    【解决方案2】:

    您应该在app-header 的模板中使用myComponent 的选择器...

    假设你的模板中有HeaderComponent 你应该包括你的app-my-component like: template: &lt;app-my-component&gt;&lt;/app-my-component&gt;

    【讨论】:

    • 也许我的问题不够清楚。 MyComponent 实际上是动态的,并且在每个模块中都会有所不同。我找到了一种方法,但是组件必须放在模块中的“entryComponents”中。
    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    相关资源
    最近更新 更多