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

我有以下模板:

<div>

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

</div>

并最终以:

<div "let a = aVariable">

<span>{{a}}</span>

</div>

有办法吗?

回答:

回答:

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

@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);

}

}

通过此*ngVar指令,我们可以使用以下命令

<div *ngVar="false as variable">

<span>{{variable | json}}</span>

</div>

要么

<div *ngVar="false; let variable">

<span>{{variable | json}}</span>

</div>

要么

<div *ngVar="45 as variable">

<span>{{variable | json}}</span>

</div>

要么

<div *ngVar="{ x: 4 } as variable">

<span>{{variable | json}}</span>

</div>

回答:

角v4

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

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

<span>{{variable.a}}</span>

<span>{{variable.b}}</span>

<span>{{variable.c}}</span>

</div>

export class AppComponent {

x = 5;

}

3)如果您不想创建包装器div,可以使用ng-container

<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>

正如@基思在评论中提到的

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

有关其他方法,请参见更新。

以上是 如何在Angular的模板中声明变量 的全部内容, 来源链接: utcz.com/qa/432003.html

回到顶部