You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中父组件值变更时如何更新子组件值?

问题原因

你的子组件仅在ngOnInit生命周期钩子中初始化updatedRows,而ngOnInit只会在组件首次加载时执行一次。当父组件更新Nwrows的值后,子组件不会自动重新执行赋值逻辑,因此无法同步最新数据。

解决方案

方案1:实现ngOnChanges监听输入变更

利用OnChanges钩子监听Nwrows的变化,每次输入属性更新时重新处理数组:

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

@Component({
  selector: 'my-child',
  template: `
  <h1>{{Nwname}}</h1>
  <ul>
    <li *ngFor="let item of updatedRows">{{item.TelephoneNo}}</li>
  </ul>
  `,
  styles: [],
})
export class ChildComponent implements OnInit, OnChanges {
  @Input() Nwname;
  @Input() Nwrows;
  updatedRows;

  ngOnInit() {
    this.updateRows();
  }

  ngOnChanges(changes: SimpleChanges) {
    // 检测Nwrows是否发生变更
    if (changes.Nwrows) {
      this.updateRows();
    }
  }

  private updateRows() {
    // 用扩展运算符创建新数组,避免直接引用父组件数据
    this.updatedRows = [...this.Nwrows];
  }
}

方案2:使用getter属性实时返回处理后的数据

通过getter属性,每次模板渲染时都会基于最新的Nwrows生成新数组,无需手动监听变更:

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

@Component({
  selector: 'my-child',
  template: `
  <h1>{{Nwname}}</h1>
  <ul>
    <li *ngFor="let item of updatedRows">{{item.TelephoneNo}}</li>
  </ul>
  `,
  styles: [],
})
export class ChildComponent implements OnInit {
  @Input() Nwname;
  @Input() Nwrows;

  ngOnInit() {}

  get updatedRows() {
    return [...this.Nwrows];
  }
}

额外注意:父组件数组更新方式

如果父组件是修改数组内部元素(比如push、splice),Angular的变更检测无法感知引用未变的数组。此时父组件需要创建新数组引用触发变更,比如:

// 错误方式:仅修改数组内容,引用未变
this.Nwrows.push(newItem);

// 正确方式:创建新数组,更新引用
this.Nwrows = [...this.Nwrows, newItem];

内容的提问来源于stack exchange,提问作者3gwebtrain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:55:18