我的CoreComponent
告诉我的NotificationsService
显示新通知并在content
属性中传递一个html字符串:
export class CoreComponent {
constructor(private _notificationsService: NotificationsService) {
this._notificationsService.show({content: '<h1 (click)="close()">hej hej</h1>'});
}
}
然后,在 NotificationsService
将通知转发给组件后,我的 NotificationsComponent
开始发挥作用,该组件必须呈现一个假组件,以便在 html 上设置所有绑定(bind)和指令在 content
中将起作用:
export class NotificationsComponent {
public notifications: string[] = [];
constructor(private _notificationsService: NotificationsService, dcl: DynamicComponentLoader, elementRef: ElementRef, injector: Injector) {
_notificationsService.newNotification$.subscribe(
notification => {
this.notifications.push(notification);
if (notification.content) {
dcl.loadIntoLocation(toComponent(notification.content, []), elementRef, 'content');
function toComponent(template, directives = []) {
@Component({
selector: 'custom-content',
template: template,
directives: directives
})
class FakeComponent {}
return FakeComponent;
}
}
}
)
}
}
然后它使用 *ngFor
循环呈现通知:
<div>
<ul>
<li *ngFor="#notification of notifications">
<div #content></div>
</li>
</ul>
</div>
问题是它由于某种原因找不到#content
变量,它只是抛出一个Uncaught Could not find variable content
。我的猜测是因为它在循环内,但我真的不知道为什么会这样。
如何将这个假组件渲染到通知模板中(最好是在将通知
推送到公共(public)通知
之前,以便在显示新通知时该组件实际上从一开始就存在)?
编辑:我发现,如果没有*ngFor
,我的代码就可以工作,但是循环中的一些问题导致了这里的问题。有谁知道为什么会发生这种情况?
最佳答案
要解决 ngFor
问题,您可以创建一个包装器元素来执行实际的 dcl.loadIntoLocation()
此包装器组件是为每个通知
添加的,并获取传递的组件,然后将其添加到自身内部。
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private containerRef:ViewContainerRef, private dcl:DynamicComponentLoader) {}
@Input() component;
ngOnChanges() {
if(this.cmpRef) {
throw 'currently changing type after the component was added is not supported'
}
this.dcl.loadNextToLocation(this.component, this.containerRef).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'core-comp',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let notification of notifications">
<dcl-wrapper [component]="notification"></dcl-wrapper>
</div>
`
})
export class NotificationsComponent {
public notifications: string[] = [];
...
}
就像Angular 2 dynamic tabs with user-click chosen components中也解释的那样
关于angular - 无法在 Angular 2 中的 *ngFor 中找到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36423941/