角10-其他组件中的负载组件

  • 本文关键字:组件 负载 其他 angular
  • 更新时间 :
  • 英文 :


在AngularJS中,可以使用$compile In模板加载组件。

我试着用Angular 10这样做:

import {AfterViewInit, Component, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef, ComponentRef} from '@angular/core';
import { LoginFormComponent } from '../../component/login-form/login-form.component';
@Component({
selector: 'app-on-boarding',
templateUrl: './on-boarding.component.html',
styleUrls: ['./on-boarding.component.sass']
})
export class OnBoardingComponent implements OnInit, AfterViewInit {
@ViewChild('container', {read: ViewContainerRef}) target: ViewContainerRef;

private readonly componentFactoryResolver: ComponentFactoryResolver;
constructor(componentFactoryResolver: ComponentFactoryResolver) {
this.componentFactoryResolver = componentFactoryResolver;
}
ngAfterViewInit(): void {
const factory = this.componentFactoryResolver.resolveComponentFactory(LoginFormComponent);
const component = this.target.createComponent(factory);
console.log(factory);
console.log(component);
}
ngOnInit(): void {
}
}

模板'/正在登机。component.html':

<div #container></div>

但什么也没发生。没有错误,#容器中没有加载组件。

#container为孩子寻址只是工作的一半。您需要正确地包含子组件。如果你的孩子看起来接近这个:

@Component({
selector: 'app-container',
...
})

然后你父母的模板应该是这样的:

<app-container #container></app-container>

进一步阅读:https://angular.io/api/core/ViewChild

感谢您的回答。

我有一个叫做";登机时";。在这方面,我想动态地加载其他组件;步骤1";或";步骤2";。。。

我不想在";登机时";

<app-step-1 *ngIf="..."></app-step-1>
<app-step-2 *ngIf="..."></app-step-2>
<app-step-3 *ngIf="..."></app-step-3>

当我可以在ViewChild中使用模板时,这可能是一个解决方案,但我不知道,如果可能的话。

最新更新