Search code examples
htmlangulartypescriptdata-bindingangular2-template

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?


Solution

  • 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