ngIf=false with ngContent 仍然加载模板绑定

ngIf=false with ngContent still loads template bindings

定义一个简单的组件如下:

@Component({
  selector: 'loader',
  template: `<div *ngIf='false'>
        <ng-content></ng-content>
        </div>`,
})
export class Loader {}

像这样使用时:

  <loader>
      {{model.something}}
  </loader>

如果模型在父项中未定义,我仍然会收到模板绑定错误,因为即使使用 ngIf=false,它也会尝试解析绑定。为什么会这样?

因为要投影到 ngContent 元素内的 loader 组件的内部内容会使用当前组件上下文 (this) 编译一次,即使组件模板是'注入到 DOM.

它的工作方式与 ng-transclude 在 Angular 1.X

中的工作方式相同

你应该在这里使用Elvis Operator来避免这样的问题

<loader>
    {{model?.something}}
</loader>