Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'this' keyword in Angular component's template

Let's say we have a prop variable in the component class and we use it via interpolation in the template (stackblitz demo):

component class:

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

template:

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

Why in Angular it's possible to use this keyword in templates without any warnings/error (even in AOT mode)? What's behind it?

Edit

According to the remark in the answer: this refers to the component itself for which the template was rendered. But I can also create a template variable and access to it using this:

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

In this case we don't have an inp variable in the component class and I still get the access to it using {{this.inp...}}. Magic?

like image 923
shohrukh Avatar asked Sep 03 '18 15:09

shohrukh


2 Answers

I don't think somebody can give a very much exact answer here (maybe somebody from Angular CLI team), however the outcome I came to is that the component renderer fully ignores this keyword in the places where it seems valid (with some exceptions).

Proof

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

One can assume from the above that this is similar to AngularJS (angular 1) scope, where the scope contains the component properties.

It does not explain why heroInput is not listed in this | json still.

However the following is totally broken:

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

It gives an error: cannot get value of undefined. It should, not, it must work, unless (the only explanation) this is just ignored in every case but

{{ this | json }}

where it refers to the component, because this is the only way to debug the whole component object from the template. Maybe there are some other exceptions, still.

Updated stackblitz

like image 57
smnbbrv Avatar answered Oct 24 '22 00:10

smnbbrv


this refers to the component itself for which the template was rendered. On the template you can access only members of the component. This means that this is implicitly added to each property which you use in the template.

This two accesses are the same - the 2nd one implicitly use this in front of it.

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

The same is when you use this in the component. When you want to access prop in the component you need to prefix it with this.prop to inform that you are accessing property of the component, not a local variable.

like image 24
Suren Srapyan Avatar answered Oct 24 '22 00:10

Suren Srapyan