在 Angular 模板中创建本地绑定上下文

Create local binding context in Angular template

假设我绑定了一个深度嵌套的对象图:

<div>{{model.rootProperty}}</div>

<div>
    <div>{{model.some.deeply.nested.property.with.a.donut.name}}</div>
    <div>{{model.some.deeply.nested.property.with.a.donut.calories}}</div>
    <div>{{model.some.deeply.nested.property.with.a.donut.deliciousness}}</div>
</div>

我不想重复访问器链。我知道我可以在我的视图模型上公开一个 属性,但我更愿意以某种方式创建本地上下文。我想要的语法是这样的:

<div>{{model.rootProperty}}</div>

<div [binding-context]="model.some.deeply.nested.property.with.a.donut">
    <div>{{name}}</div>
    <div>{{calories}}</div>
    <div>{{deliciousness}}</div>
</div>

我该怎么做?

我尝试创建一个组件,其模板仅包含 <ng-content></ng-content>,但以这种方式嵌入的内容仍然具有组件父组件的上下文。

我知道我可以将内部内容包装在 <template> 中并在我的组件中使用模板插座,但这比我想要的更多标记,而且 *ngFor 似乎没有不需要这个。

这可能吗?

可以定义类似于 *ngIf 和 *ngFor 的结构指令,称为 *bindingContext:

<div *bindingContext = "let  a_variable  be  an_expression">

Angular 使用这种语法在幕后做了很多魔术。首先,asterics 创建了一个立即使用的 。然后评估微语法并调用名为 bindingContextBe 的指令。该指令使 an_expression 在模板上下文中作为 $implicit 可用,而模板上下文又被分配给 a_variable

Angular documentation中有完整的解释。

我实现了 BindingContext 如下:

import {Directive, EmbeddedViewRef, Input, 
        TemplateRef, ViewContainerRef} from '@angular/core';

@Directive({selector: '[bindingContextBe]'})
export class BindingContextDirective {
  private context = new BindingContextDirectiveContext();
  private viewRef: EmbeddedViewRef<BindingContextDirectiveContext>|null = null;

  constructor(private viewContainer: ViewContainerRef,
      private templateRef: TemplateRef<BindingContextDirectiveContext>) {
  }

  @Input()
  set bindingContextBe(context: any) {
    this.context.$implicit = context;
    if (!this.viewRef) {
      this.viewContainer.clear();
      this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef,
                                                           this.context);
    }
  }
}

export class BindingContextDirectiveContext {
  public $implicit: any = null;
}

用法示例:

Full:

<div>
    <div>{{model.some.deeply.nested.property.with.a.donut.name}}</div>
    <div>{{model.some.deeply.nested.property.with.a.donut.calories}}</div>
    <div>{{model.some.deeply.nested.property.with.a.donut.deliciousness}}</div>
    <input [(ngModel)]="model.some.deeply.nested.property.with.a.donut.name">
</div>

<hr>

Alias:

<div *bindingContext="let food be model.some.deeply.nested.property.with.a.donut">
    <div>{{food.name}}</div>
    <div>{{food.calories}}</div>
    <div>{{food.deliciousness}}</div>
    <input [(ngModel)]="food.name">
</div>

PS: 不要忘记在你的模块中声明方向。