The Angular parent component re-requests the interface to obtain data, uses @Input() to pass the data, and the child component does not update the view

In Angular, when the parent component re-requests the interface and gets new data, it needs to pass the new data to the child components and notify them to update their views.

Use the @Input decorator to pass data from parent components to child components.

In the parent component, pass the new data to the child component:

<app-child [data]="newData"></app-child>

In the child component, receive data through the @Input decorator:

@Input() data: any;

When the data changes, the child component will automatically update the view as usual.

However, there are some special cases:

1. If the child component's change detection strategy is OnPush, you must manually tell Angular that the current component's input property has changed. This way, Angular can properly update the view.

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

@Component({
  selector: 'app-child',
  template: '<p>{
   
   { data }}</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
  @Input() data: any;

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnChanges() {
    this.cdr.markForCheck();
  }
}

2. If the update is reference type data in the parent component, such as an array or object, and the child component @Input()refers to these data through etc., you may need to manually process these data to ensure that the child component can respond to the update correctly.

For example, a shallow copy can be used to create a new array when updating array data:

// 更新数据并创建新的数组
this.myArray = [...this.myArray, newValue];

If the child component has its own init method, you can use the ngOnChanges lifecycle hook to watch for changes in input property values ​​and call your custom init method to update the view.

Add ngOnChanges hook in child component:

ngOnChanges(changes: SimpleChanges) {
  if (changes.data) {
    // 获取新值
    this.data = changes.data.currentValue;
    // 调用init方法,刷新视图
    this.initTable(this.data);
  }
}

Guess you like

Origin blog.csdn.net/qq_38679823/article/details/130344288