我有以下模板:

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

并希望以:

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

有办法吗?


当前回答

更新3

问题https://github.com/angular/angular/issues/2451在Angular 4.0.0中已修复

另请参阅

https://github.com/angular/angular/pull/13297 https://github.com/angular/angular/commit/b4db73d https://github.com/angular/angular/issues/13061

更新2

这是不支持的。

有模板变量,但不支持分配任意值。它们只能用于引用它们应用的元素,导出指令或组件的名称,以及ngFor等结构指令的作用域变量,

参见https://github.com/angular/angular/issues/2451

更新1

@Directive({
  selector: '[var]',
  exportAs: 'var'
})
class VarDirective {
  @Input() var:any;
}

然后像这样初始化

<div #aVariable="var" var="abc"></div>

or

<div #aVariable="var" [var]="'abc'"></div>

然后用这个变量

<div>{{aVariable.var}}</div>

(未测试)

# variable创建对VarDirective的引用(exportAs: 'var') var="abc"实例化VarDirective,并将字符串值"abc"传递给它的值输入。 aVariable。Var读取分配给Var指令Var输入的值。

其他回答

对某人有帮助的简短回答

模板引用变量经常引用DOM元素 模板。 也可以参考angular或web组件和指令。 这意味着您可以轻松地访问模板中的任何地方的变量

使用哈希符号(#)声明引用变量 是否能够将变量作为事件的参数传递

  show(lastName: HTMLInputElement){
    this.fullName = this.nameInputRef.nativeElement.value + ' ' + lastName.value;
    this.ctx.fullName = this.fullName;
  }

但是,你可以使用ViewChild装饰器在你的组件中引用它。

import {ViewChild, ElementRef} from '@angular/core';

在Component中引用firstNameInput变量

@ViewChild('firstNameInput') nameInputRef: ElementRef;

之后,你可以在组件中的任何地方使用this.nameInputRef。

使用ng-template

对于ng-template,略有不同,因为每个模板都有自己的一组输入变量。

https://stackblitz.com/edit/angular-2-template-reference-variable

它简单得多,不需要任何额外的东西。在我的例子中,我声明变量“open”,然后使用它。

   <mat-accordion class="accord-align" #open>
      <mat-expansion-panel hideToggle="true" (opened)="open.value=true" (closed)="open.value=false">
        <mat-expansion-panel-header>
          <span class="accord-title">Review Policy Summary</span>
          <span class="spacer"></span>
          <a *ngIf="!open.value" class="f-accent">SHOW</a>
          <a *ngIf="open.value" class="f-accent">HIDE</a>
        </mat-expansion-panel-header>
        <mat-divider></mat-divider>
        <!-- Quote Details Component -->
        <quote-details [quote]="quote"></quote-details>
      </mat-expansion-panel>
    </mat-accordion>

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

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

组件中的方法可以是

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

我的建议是:https://medium.com/@AustinMatherne/ angular-let-direcy-a168d4248138

这个指令允许你这样写:

<div *ngLet="'myVal' as myVar">
  <span> {{ myVar }} </span>
</div>

对于那些决定使用结构指令代替*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语言服务无法识别变量类型,因此模板中没有代码补全功能。我希望它能很快修好。