Angular @input change detection | Angular 12

In this article we’ll work with a simple example, passing data from parent component to child component and resolving Angular @input change detection in the child component by using LifeCycle Hook and Angular @input setter

The Change detection means updating the template (document object model) when the data changed. in the Angular 12 ChangeDetectionStrategy.Default change detection, whenever any data is changed, Angular change detection checks for all components from root to child component. by using ChangeDetectionStrategy.onPushc change detection, Angular will check the change of the Input references and d skip unnecessary checks for this component and all its child components.

Using OnChanges LifeCycle Hook

NgOnChanges gives you more control to watch how the data changes happing in a component.

Let’s use ngOnChanges(changes: SimpleChanges) method to app.component.ts. Inside ngOnChanges method, let’s check for current value (change?.employeeId?.currentValue), then call a API to get employee details . basically ngOnChanges() get all changes at once if our component has several @Input().

export class EmployeeDetailsComponent {
  @Input() employeeName: string;
  employeeDetails: IEmployee;

  constructor(private _http: HttpClient) {
    this.employeeDetails = { name: '', complayName: '', employeeId: '' }
  }

  ngOnChanges(change: SimpleChanges) {
    if (change?.employeeId?.currentValue)
      this.getEmployeeDetails(change.employeeId.currentValue)
  }

  getEmployeeDetails(empName: string) {
    const employeeFileName = `${empName}.json`;
    this._http.get<IEmployee>(`${environment.resoucePath}/${employeeFileName}`).subscribe(res => {
      this.employeeDetails = res;
    })
  }
} 

In above code we are retrieve the latest value for the employeeId

Using Angular @input setter

Angular @input setter, in Angular @input change detection when the component has a small number of inputs  a setter is probably the better approach.

Below code snippet  is an example of employeeId property changes using setter.

export class EmployeeDetailsComponent {

  @Input() set employeeID(value: string) {
    if (value !== undefined) {
      this.getEmployeeDetails(value);
    }
  }

  constructor(private _http: HttpClient) {
  }

  getEmployeeDetails(empName: string) {
    const employeeFileName = `${empName}.json`;
    this._http.get<IEmployee>(`${environment.resoucePath}/${employeeFileName}`).subscribe(res => {
      console.log(res);
    })
  }
} 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

  • Post category:Angular
  • Reading time:3 mins read