In Angular code (TypeScript), "this" refers to the current instance of the class — for example the component or service object. Angular creates the instance, and you use this to access its properties and methods. @Component({ selector: 'app-counter', template: `<button (click)="increment()">{{ count }}</button>` }) export class CounterComponent { count = 0; increment() { this.count++; } // this = this CounterComponent instance } In templates you do not write this; Angular evaluates expressions against the component instance automatically, so {{ count }} means this.count. (Angular does support explicit this in templates, but it is rarely needed.) The classic pitfall: losing "this" in callbacks In JavaScript, the value of this depends on how a function is called. Passing a class method as a callback can lose the binding: setTimeout(this.refresh, 1000); // inside refresh, this is undefined in strict mode — bug Fixes: - Arrow functions capture this from the surrounding scope: setTimeout(() => this.refresh(), 1000); this.http.get<Item[]>(url).subscribe(items => this.items = items); - Define the method as an arrow-function property: refresh = () => { ... }; - Use bind: setTimeout(this.refresh.bind(this), 1000); This matters for RxJS subscriptions, event listeners added with addEventListener, third-party library callbacks and timers. Other points: - In constructors with parameter properties (constructor(private api: ApiService)), the dependency is available as this.api. With inject(), you assign it to a field and use this.api the same way. - Inside a normal function declared with the function keyword, this is not the component — avoid such functions in component code, or prefer arrow functions. - Static members are accessed through the class name, not this. Understanding this is mainly about JavaScript function binding; Angular itself just provides the class instances.
Ravindra Wadile · · 0 likes