无法在 Angular 2 中的 *ngFor 中找到变量

Unable to find variable inside *ngFor in Angular 2

我的 CoreComponent 告诉我的 NotificationsService 显示新通知并在 content 属性:

中传递一个 html 字符串
export class CoreComponent {

  constructor(private _notificationsService: NotificationsService) {
    this._notificationsService.show({content: '<h1 (click)="close()">hej hej</h1>'});
  }
}

然后我的 NotificationsComponentNotificationsService 将通知转发给组件后开始发挥作用,该组件必须呈现一个假组件,以便在 html 上设置所有绑定和指令在 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。我的猜测是因为它在一个循环中,但我真的不知道为什么会这样。

如何将这个假组件渲染到通知模板中(最好是在将 notification 推入 public notifications 之前,以便在显示新通知时该组件实际上从一开始就在那里)?

编辑: 我发现如果没有 *ngFor 我的代码就可以工作,但是循环中有一些问题导致了这里的问题。有谁知道为什么会这样?

要解决 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[] = [];
  ...
}

中也有解释