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?
I felt we can't get a proper explanation on this but,
In here it might go wrong, if i don't use this.member (In my case it was actually
this[member]
).Create a member in component like,
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
One can assume from the above that
this
is similar to AngularJS (angular 1)scope
, where thescope
contains the component properties.It does not explain why heroInput is not listed in
this | json
still.However the following is totally broken:
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 butwhere 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
this
refers to the component itself for which the template was rendered. On the template you can access onlymembers
of the component. This means thatthis
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.The same is when you use
this
in the component. When you want to accessprop
in the component you need to prefix it withthis.prop
to inform that you are accessingproperty
of the component, not a local variable.