我正在用ngComponentOutlet动态创建一个组件.
听起来好像:
听起来好像:
import {Component,NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'alert-success',template: ` <p>Alert success</p> `,}) export class AlertSuccessComponent { } @Component({ selector: 'alert-danger',template: ` <p>Alert danger</p> `,}) export class AlertDangerComponent { test = 'danger...'; } @Component({ selector: 'my-app',template: ` <h1>Angular version 4</h1> <ng-container *ngComponentOutlet="alert"></ng-container> <button (click)="changeComponent()">Change component</button> `,}) export class App { alert = AlertSuccessComponent; changeComponent() { this.alert = AlertDangerComponent; alert(this.alert.test); <-- ??????? } } @NgModule({ imports: [ BrowserModule ],declarations: [ App,AlertSuccessComponent,AlertDangerComponent ],entryComponents: [AlertDangerComponent,AlertSuccessComponent],bootstrap: [ App ] }) export class AppModule {}
在changeComponent()中,我尝试(天真地猜测)获取当前组件的引用以用数据提供它,但它失败了:(
我应该使用ViewContainerRef,怎么样?
解决方法
您必须直接将组件名称放在那里:
<ng-container *ngComponentOutlet="AlertDangerComponent; ngModuleFactory: alertDangerModule;"></ng-container>
我冒昧地添加了模块,用于从不同于当前模块的模块渲染组件时.
此外,要使用“模块”选项,您需要在当前组件中使用此选项:
private alertDangerModule: NgModuleFactory<any>; constructor(private compiler: Compiler) { this.alertDangerModule = compiler.compileModuleSync(AlertDangerModule); }
如果您只想从当前模块加载1个组件,那么您需要执行以下操作:
<ng-container *ngComponentOutlet="AlertDangerComponent"></ng-container>
导入模块:NgModuleFactory
更新(动态):
创建一个向量,例如:
import AlertDangerComponent from './path'; import AlertSuccessComponent from './path'; export const MY_ALERTS = { 'alertDanger': AlertDangerComponent,'alertSuccess': AlertSuccessComponent,};
在组件中,导入MY_ALERTS,您可以渲染与MY_ALERTS一样多的组件.
或者您可以尝试通过创建新的ng-container动态渲染它(尚未测试).
我正在使用它来渲染包含组件类的巨大向量中的组件以及其他值,例如布尔值,因此我知道每次加载哪个组件.
要渲染此向量中的组件,您可以:
<div *ngFor="let alert of MY_ALERTS | keys"> <ng-container *ngComponentOutlet="MY_ALERTS[alert]; ngModuleFactory: commonAlertsModule;"></ng-container> </div>
其中key只是一个@Pipe,它返回一个对象的键(而不是值).
更新(替代方法):
我想也许你可能对这个其他方法感兴趣:使用@Component作为’指令’.我会自己解释一下:
使用像selector这样的指令声明你的组件:
@Component({ selector: '[alert-success]',}) export class AlertSuccessComponent { } @Component({ selector: '[alert-danger]',}) export class AlertDangerComponent { test = 'danger...'; }
然后,根据场合,您只需拨打一个或另一个:
@Component({ selector: 'my-app',template: ` <h1>Angular version 4</h1> <div *ngIf="alertDanger" alert-danger></div> <div *ngIf="alertSuccess" alert-success></div> <button (click)="changeComponent()">Change component</button> `,}) export class App { alertSuccess = true; alertDanger = false; changeComponent() { this.alertSuccess = !this.alertSuccess; this.alertDanger = !this.alertDanger; } }
在我的示例中(虽然未经过测试)我初始化成功警报.单击时,它应将alertSuccess设置为false并将alertDanger设置为true.