我有以下模板:

<div>
  <span>{{aVariable}}</span>
</div>

并希望以:

<div "let a = aVariable">
  <span>{{a}}</span>
</div>

有办法吗?


当前回答

我试图做一些类似的事情,看起来这个问题已经在angular的新版本中得到了解决。

    <div *ngIf="things.car; let car">
      Nice {{ car }}!
    </div>
    <!-- Nice Honda! -->

其他回答

对于那些决定使用结构指令代替*ngIf的人,请记住,默认情况下指令上下文不进行类型检查。要创建一个类型安全的指令,应该添加ngTemplateContextGuard属性,请参见输入指令的上下文。例如:

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

@Directive({
    // don't use 'ng' prefix since it's reserved for Angular
    selector: '[appVar]',
})
export class VarDirective<T = unknown> {
    // https://angular.io/guide/structural-directives#typing-the-directives-context
    static ngTemplateContextGuard<T>(dir: VarDirective<T>, ctx: any): ctx is Context<T> {
        return true;
    }

    private context?: Context<T>;

    constructor(
        private vcRef: ViewContainerRef,
        private templateRef: TemplateRef<Context<T>>
    ) {}

    @Input()
    set appVar(value: T) {
        if (this.context) {
            this.context.appVar = value;
        } else {
            this.context = { appVar: value };
            this.vcRef.createEmbeddedView(this.templateRef, this.context);
        }
    }
}

interface Context<T> {
    appVar: T;
}

该指令可以像*ngIf一样使用,除了它可以存储假值:

<ng-container *appVar="false as value">{{value}}</ng-container>

<!-- error: User doesn't have `nam` property-->
<ng-container *appVar="user as user">{{user.nam}}</ng-container>

<ng-container *appVar="user$ | async as user">{{user.name}}</ng-container>

与*ngIf相比,唯一的缺点是Angular语言服务无法识别变量类型,因此模板中没有代码补全功能。我希望它能很快修好。

如果你想要得到函数的响应并将其设置为变量,你可以像下面这样在模板中使用它,使用ng-container来避免修改模板。

<ng-container *ngIf="methodName(parameters) as respObject">
  {{respObject.name}}
</ng-container>

组件中的方法可以是

methodName(parameters: any): any {
  return {name: 'Test name'};
}

你可以使用Angular 2中的template元素或Angular 4+中的ng-template在html代码中声明变量。

模板有一个上下文对象,它的属性可以使用let绑定语法分配给变量。注意,您必须为模板指定一个出口,但它可以是对模板本身的引用。

<ng-template #selfie [ngTemplateOutlet]="selfie"
    let-a="aVariable" [ngTemplateOutletContext]="{ aVariable: 123 }">
  <div>
    <span>{{a}}</span>
  </div>
</ng-template>

<!-- Output
<div>
  <span>123</span>
</div>
-->

您可以通过使用context对象的$implicit属性而不是自定义属性来减少代码量。

<ng-template #t [ngTemplateOutlet]="t"
    let-a [ngTemplateOutletContext]="{ $implicit: 123 }">
  <div>
    <span>{{a}}</span>
  </div>
</ng-template>

上下文对象可以是文字对象或任何其他绑定表达式。其他有效例子:

<!-- Use arbitrary binding expressions -->
<ng-template let-sum [ngTemplateOutletContext]="{ $implicit: 1 + 1 }">

<!-- Use pipes -->
<ng-template let-formatPi [ngTemplateOutletContext]="{ $implicit: 3.141592 | number:'3.1-5' }">

<!-- Use the result of a public method of your component -->
<ng-template let-root [ngTemplateOutletContext]="{ $implicit: sqrt(2116) }">

<!--
    You can create an alias for a public property of your component:
    anotherVariable: number = 123; 
-->
<ng-template let-aliased [ngTemplateOutletContext]="{ $implicit: anotherVariable }">

<!--
    The entire context object can be bound from a public property:
    ctx: { first: number, second: string } = { first: 123, second: "etc" }
-->
<ng-template let-a="first" let-b="second" [ngTemplateOutletContext]="ctx">

我喜欢创建一个指令来做这件事的方法(很好的调用@yurzui)。

最后我在Medium上找到了一篇文章,Angular的“let”指令很好地解释了这个问题,并提出了一个自定义的let指令,它在我的用例中工作得很好,代码更改很少。

以下是要点(在发布时)和我的修改:

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

interface LetContext <T> {
  appLet: T | null
}

@Directive({
  selector: '[appLet]',
})
export class LetDirective <T> {
  private _context: LetContext <T> = { appLet: null }

  constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef <LetContext <T> >) {
    _viewContainer.createEmbeddedView(_templateRef, this._context)
  }

  @Input()
  set appLet(value: T) {
    this._context.appLet = value
  }
}

我的主要改变是:

将前缀从'ng'更改为'app'(你应该使用你的应用程序的自定义前缀是什么) 将appLet: T更改为appLet: T | null

不知道为什么Angular团队还没有发布一个官方的ngLet指令。

原始源代码归功于@AustinMatherne

@yurzui的原始答案将不能从Angular 9开始工作,因为一个奇怪的问题,将Angular 8应用程序迁移到9。 然而,你仍然可以从ngVar指令中受益

<ng-template [ngVar]="variable">
your code
</ng-template>

尽管它可能会导致IDE警告:“变量未定义”