skip to content
Alvin Lucillo

Preserve this context

/ 2 min read

💻 Tech

Suppose you have the parent and child components (see below). You may encounter this error displayed at the console tab. This is because someFunc is using a regular function which doesn’t preserve the context of surrounding this. someFunc refers to this.getLogValue() and is passed to the child component. By the time the child component is rendered, someFunc wouldn’t find this.getLogValue() because it already lost the context. The solution is to use arrow function as it captures the context surround this upon definition, so when it’s passed to another component, it can call getLogValue.

Error:

main.ts:5 ERROR TypeError: this.getLogValue is not a function
    at _ChildComponent.someFunc [as someFn] (parent.component.ts:14:22)

Solution:

  someFunc = () => {
    console.log(this.getLogValue())
  }

Sample components:

// parent.component.ts
import { Component } from '@angular/core';
import { ChildComponent } from "../child/child.component";

@Component({
  selector: 'app-parent',
  standalone: true,
  imports: [ChildComponent],
  templateUrl: './parent.component.html',
  styleUrl: './parent.component.css'
})
export class ParentComponent {

  public someFunc() {
    console.log(this.getLogValue())
  }

  getLogValue(): string {
    return "hello world";
  }

}
<!-- parent.component.html -->
<p>parent works!</p>
<app-child [someFn]="someFunc"></app-child>
// child.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  standalone: true,
  imports: [],
  templateUrl: './child.component.html',
  styleUrl: './child.component.css'
})
export class ChildComponent implements OnInit {
@Input() someFn!: () => void

constructor() {

}
  ngOnInit(): void {
    this.someFn();
  }
}