在Angular组件的模板中使用'this'关键字

问题描述 投票:2回答:2

假设我们在组件类中有一个prop变量,我们通过模板中的插值(stackblitz demo)使用它:

组件类:

@Component({...})
export class AppComponent  {
  prop = 'Test';
  ...
}

模板:

<p>{{ this.prop }}</p>
<p>{{ prop }}</p>

为什么在Angular中可以在模板中使用this关键字而没有任何警告/错误(即使在AOT模式下)?背后是什么?

编辑

根据答案中的评论:this指的是为其呈现模板的组件本身。但我也可以创建一个模板变量并使用this访问它:

<input #inp> {{ this.inp.value }}

在这种情况下,我们在组件类中没有inp变量,我仍然可以使用{{this.inp...}}访问它。魔法?

angular typescript data-binding angular2-template
2个回答
1
投票

我不认为有人可以在这里给出一个非常准确的答案(也许是来自Angular CLI团队的人),但是我得出的结果是组件渲染器完全忽略this关键字在它似乎有效的地方(有一些例外) 。

证明

<input #heroInput value="0">
This prints the component JSON without heroInput: {{ this | json }}

<input #heroInput value="0">
This prints 0: {{ this.heroInput.value }}

<div *ngFor="let val of [1,2,3]">
  <input #heroInput [value]="val">
  Overrides heroInput with current value: {{ this.heroInput.value }}
</div>

This prints 0: {{ this.heroInput.value }}

从上面可以假设this类似于AngularJS(角度1)scope,其中scope包含组件属性。

它没有解释为什么还没有在this | json中列出heroInput。

但是以下内容完全被打破:

{{ this['heroInput'].value }}

它给出了一个错误:无法获得未定义的value。它应该,但不是,它必须工作,除非(唯一的解释)this在每种情况下都被忽略但是

{{ this | json }}

它引用组件的位置,因为这是从模板调试整个组件对象的唯一方法。也许还有其他一些例外。

更新了stackblitz


1
投票

this指的是为其呈现模板的组件本身。在模板上,您只能访问组件的members。这意味着this隐式添加到您在模板中使用的每个属性中。

这两个访问是相同的 - 第二个访问隐含地使用this在它前面。

<p>{{ this.prop }}</p>
<p>{{ prop }}</p>

在组件中使用this时也是如此。如果要在组件中访问prop,则需要在其前面添加this.prop,以通知您正在访问组件的property,而不是本地变量。

© www.soinside.com 2019 - 2024. All rights reserved.