我的CoreComponent
告诉我的NotificationsService
显示新通知,并在content
属性中传递html字符串:
export class CoreComponent {
constructor(private _notificationsService: NotificationsService) {
this._notificationsService.show({content: '<h1 (click)="close()">hej hej</h1>'});
}
}
然后我的NotificationsComponent
在NotificationsService
将通知转发给组件后发挥作用,此组件必须呈现假组件,以便在content
中的html上设置所有绑定和指令会工作:
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
。我的猜测是因为它在循环中,但我真的不知道为什么会这样。
如何将此虚假组件呈现到通知模板中(最好在将notification
推送到public notifications
之前,以便组件在显示新通知时从一开始实际存在?)
编辑:我发现没有*ngFor
我的代码可以正常工作,但是这里有一些导致问题的循环。有谁知道为什么会这样?
答案 0 :(得分:2)
要解决ngFor
问题,您可以创建一个执行实际dcl.loadIntoLocation()
为每个notification
添加此包装器组件,并获取传递的组件,然后在其内部添加。
@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[] = [];
...
}
中解释