【发布时间】:2017-11-18 23:01:58
【问题描述】:
我正在使用 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,如何?
【问题讨论】:
-
我认为没有办法获取组件。我看到了一个拉取请求来添加它,但它看起来不像被接受。您可以自己创建和添加组件,然后获得对创建的组件实例的引用,并且可以更新其属性。另见github.com/angular/angular/blob/… 和stackoverflow.com/questions/36325212/…
-
@GünterZöchbauer 我误解了 OP,以为他只需要渲染一个组件,但没有意识到必须动态进行。我改变了方法,检查一下,如果你愿意/可以的话,让我知道你的想法! :D
-
我简要查看了您回答中的示例,但这并不是我理解他所要求的。我认为他应该使用我上面评论中第二个链接中演示的内容。
-
@GünterZöchbauer 也许我错过了一些东西,但在第二个链接中你建议
ngComponentOutlet,他已经在使用它了。而且,我相信我们不能使用ngComponentOutlet按需更改渲染的组件。这就是为什么在理解了 OP 之后我选择了 directive like 方法。如果我们找到ngComponentOutlet的解决方案,我将在我自己的项目中实现它! :P -
ngComponentOutlet有这个限制,它不提供对创建的组件的引用。请参阅链接答案中的 RC.7 示例。
标签: angular components