Html 如何在 Angular 的模板中声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38582293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:37:59  来源:igfitidea点击:

How to declare a variable in a template in Angular

htmlangular

提问by Scipion

I have the following template :

我有以下模板:

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

and would like to end up with :

并希望以:

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

Is there a way to do ?

有办法吗?

采纳答案by yurzui

Update

更新

We can just create directive like *ngIfand call it *ngVar

我们可以创建像这样的指令*ngIf并调用它*ngVar

ng-var.directive.ts

ng-var.directive.ts

@Directive({
    selector: '[ngVar]',
})
export class VarDirective {
  @Input()
  set ngVar(context: any) {
    this.context.$implicit = this.context.ngVar = context;
    this.updateView();
  }

  context: any = {};

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

  updateView() {
    this.vcRef.clear();
    this.vcRef.createEmbeddedView(this.templateRef, this.context);
  }
}

with this *ngVardirective we can use the following

有了这个*ngVar指令,我们可以使用以下内容

<div *ngVar="false as variable">
      <span>{{variable | json}}</span>
</div>

or

或者

<div *ngVar="false; let variable">
    <span>{{variable | json}}</span>
</div>

or

或者

<div *ngVar="45 as variable">
    <span>{{variable | json}}</span>
</div>

or

或者

<div *ngVar="{ x: 4 } as variable">
    <span>{{variable | json}}</span>
</div>

Plunker Example Angular4 ngVar

Plunker 示例 Angular4 ngVar

See also

也可以看看

Original answer

原答案

Angular v4

角 v4

1) div+ ngIf+ let

1) div+ ngIf+let

<div *ngIf="{ a: 1, b: 2 }; let variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
</div>

2) div+ ngIf+ as

2) div+ ngIf+as

view

看法

<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</div>

component.ts

组件.ts

export class AppComponent {
  x = 5;
}

3) If you don't want to create wrapper like divyou can use ng-container

3)如果你不想像div你可以使用的那样创建包装器ng-container

view

看法

<ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</ng-container>

As @Keith mentioned in comments

正如@Keith 在评论中提到的

this will work in most cases but it is not a general solution since it relies on variable being truthy

这在大多数情况下都有效,但它不是通用解决方案,因为它依赖于变量是否为真

See update for another approach.

另一种方法见更新。

回答by kayjtea

Ugly, but:

丑,但是:

<div *ngFor="let a of [aVariable]">
  <span>{{a}}</span>
</div>

When used with async pipe:

与异步管道一起使用时:

<div *ngFor="let a of [aVariable | async]">
  <span>{{a.prop1}}</span>
  <span>{{a.prop2}}</span>
</div>

回答by Steven Liekens

You can declare variables in html code by using a templateelement in Angular 2 or ng-templatein Angular 4+.

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

Templates have a context object whose properties can be assigned to variables using letbinding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.

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

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

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

You can reduce the amount of code by using the $implicitproperty of the context object instead of a custom property.

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

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

The context object can be a literal object or any other binding expression. Even pipes seem to work when surrounded by parentheses.

上下文对象可以是文字对象或任何其他绑定表达式。当被括号包围时,甚至管道似乎也能工作。

Valid examples of ngTemplateOutletContext:

的有效示例ngTemplateOutletContext

  • [ngTemplateOutletContext]="{ aVariable: 123 }"
  • [ngTemplateOutletContext]="{ aVariable: (3.141592 | number:'3.1-5') }"
  • [ngTemplateOutletContext]="{ aVariable: anotherVariable }"use with let-a="aVariable"
  • [ngTemplateOutletContext]="{ $implicit: anotherVariable }"use with let-a
  • [ngTemplateOutletContext]="ctx"where ctxis a public property
  • [ngTemplateOutletContext]="{ aVariable: 123 }"
  • [ngTemplateOutletContext]="{ aVariable: (3.141592 | number:'3.1-5') }"
  • [ngTemplateOutletContext]="{ aVariable: anotherVariable }"let-a="aVariable"
  • [ngTemplateOutletContext]="{ $implicit: anotherVariable }"let-a
  • [ngTemplateOutletContext]="ctx"哪里ctx是公共财产

回答by Günter Z?chbauer

update 3

更新 3

Issue 2451 is fixed in Angular 4.0.0

问题 2451 已在 Angular 4.0.0 中修复

See also

也可以看看

update 2

更新 2

This isn't supported.

这不受支持。

There are template variables but it's not supported to assign arbitrary values. They can only be used to refer to the elements they are applied to, exported names of directives or components and scope variables for structural directives like ngFor,

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

See also https://github.com/angular/angular/issues/2451

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

Update 1

更新 1

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

and initialize it like

并像这样初始化它

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

or

或者

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

and use the variable like

并使用变量,如

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

(not tested)

(未测试)

  • #aVariablecreates a reference to the VarDirective(exportAs: 'var')
  • var="abc"instantiates the VarDirectiveand passes the string value "abc"to it's value input.
  • aVariable.varreads the value assigned to the vardirectives varinput.
  • #aVariable创建对VarDirective( exportAs: 'var')的引用
  • var="abc"实例化VarDirective并将字符串值传递"abc"给它的值输入。
  • aVariable.var读取分配给var指令var输入的值。

回答by Aaron

Here is a directive I wrote that expands on the use of the exportAs decorator parameter, and allows you to use a dictionary as a local variable.

这是我编写的指令,它扩展了 exportAs 装饰器参数的使用,并允许您将字典用作局部变量。

import { Directive, Input } from "@angular/core";
@Directive({
    selector:"[localVariables]",
    exportAs:"localVariables"
})
export class LocalVariables {
    @Input("localVariables") set localVariables( struct: any ) {
        if ( typeof struct === "object" ) {
            for( var variableName in struct ) {
                this[variableName] = struct[variableName];
            }
        }
    }
    constructor( ) {
    }
}

You can use it as follows in a template:

您可以在模板中按如下方式使用它:

<div #local="localVariables" [localVariables]="{a: 1, b: 2, c: 3+2}">
   <span>a = {{local.a}}</span>
   <span>b = {{local.b}}</span>
   <span>c = {{local.c}}</span>
</div>

Of course #local can be any valid local variable name.

当然#local 可以是任何有效的局部变量名。

回答by monkeythedev

I would suggest this: https://medium.com/@AustinMatherne/angular-let-directive-a168d4248138

我建议这样做:https: //medium.com/@AustinMatherne/angular-let-directive-a168d4248138

This directive allow you to write something like:

该指令允许您编写如下内容:

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

回答by Philip John

In case if you want to get the response of a function and set it into a variable, you can use it like the following in the template, using ng-containerto avoid modifying the template.

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

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

And the method in the component can be something like

组件中的方法可以是这样的

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

回答by Stephen Paul

If you need autocomplete support from within in your templates from the Angular Language Service:

如果您需要来自 Angular Language Service 的模板中的自动完成支持

Synchronous:

同步:

myVar = { hello: '' };

<ng-container *ngIf="myVar; let var;">
  {{var.hello}}
</ng-container>

Using async pipe:

使用异步管道:

myVar$ = of({ hello: '' });

<ng-container *ngIf="myVar$ | async; let var;">
  {{var.hello}}
</ng-container>

回答by Hyman Rus

It is much simpler, no need for anything additional. In my example I declare variable "open" and then use it.

它更简单,不需要任何额外的东西。在我的示例中,我声明变量“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>

回答by The Mechanic

I am using angular 6x and I've ended up by using below snippet. I've a scenerio where I've to find user from a task object. it contains array of users but I've to pick assigned user.

我正在使用 angular 6x,我最终使用了以下代码段。我有一个场景,我必须从任务对象中找到用户。它包含用户数组,但我必须选择指定的用户。

<ng-container *ngTemplateOutlet="memberTemplate; context:{o: getAssignee(task) }">
</ng-container>
<ng-template #memberTemplate let-user="o">
  <ng-container *ngIf="user">
    <div class="d-flex flex-row-reverse">
      <span class="image-block">
        <ngx-avatar placement="left" ngbTooltip="{{user.firstName}} {{user.lastName}}" class="task-assigned" value="28%" [src]="user.googleId" size="32"></ngx-avatar>
      </span>
    </div>
  </ng-container>
</ng-template>