我正在创建要在父组件中加载的模板组件,具体取决于我从服务器获得的响应。我将向您提供一个简短的示例,说明我正在尝试用伪代码做什么。
这是我的 html 父组件:
<div class="parent-container">
<div *ngIf="template1"> (load template1.component) </div>
<div *ngIf="template2"> (load template2.component) </div>
etc...
</div>
然后我将拥有不同的组件(为了简洁起见,我只列出一个)
<div class="child-container">
<div> {{userName}} </div>
<div> {{contactNo}} </div>
<div> {{address}} </div>
</div>
因此,在 ngInit 上,父级向服务器发出 http 请求并获取一个值。根据父级中的值,我应该能够将子模板加载到父级中并显示它。因此,加载后,页面将如下所示:
<div class="parent-container">
<div class="child-container">
<div> {{userName}} </div>
<div> {{contactNo}} </div>
<div> {{address}} </div>
</div>
</div>
有 Angular 吗?我怎样才能创建它? 谢谢
[编辑]
我实现了 dee zg 建议的内容,这是代码:
@ViewChild(HostDirective) host: HostDirective;
OnNgInit(){}
//switch will be a response from a server
selector(switch){
switch(switch) {
case 'component1': {
this.loadComponent(Component1);
break;
}
default: {
break;
}
}
}
loadComponent(component){
var componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
var viewContainerRef = this.host;
this.viewContainerRef.clear();
var componentRef = this.viewContainerRef.createComponent(componentFactory);
(componentRef.instance);
}
这是我的主机内部的内容
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[host]',
})
export class HostDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
和 html
<ng-template host></ng-template>
有趣的是,如果 loadComponent 中的任何内容都将被加载到 OnInit 中,那么它就会起作用。如果我从 loadComponent 调用它,我会发现主机未定义。
最佳答案
在模板中:
<ng-template #yourComponentHost></ng-template>
在组件中:
@ViewChild('yourComponentHost', { read: ViewContainerRef })
yourComponentHost;
.
.
.
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(YourComponentType1);
const viewContainerRef = this.yourComponentHost;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
const yourComponentType1Instance = (<YourComponentType1>componentRef.instance);
从这里,您可以通过 yourComponentType1Instance
访问您的组件。当然,您将在 resolveComponentFactory
中执行自己的切换逻辑,以根据您想要的条件使用您需要的组件。
关于angular - 如何在父组件中动态加载 Angular 4中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590075/