采纳答案成功!
向帮助你的同学说点啥吧!感谢那些助人为乐的人
子组件如何深度监听父组件的数据?如果传进子组件一个数据
{ name: 'xiaoming', age: 12, goods: [{ price: 100 }] }
如果我父组件修改了price的值,那么我如何才能监听到呢?
如下仅供参考:
父组件将数据传递给子组件,子组件通过@Input()接收数据。
@Input()
ngOnChanges
ngOnChanges生命周期钩子可以监听@Input()绑定的属性变化。如果需要深度监听对象或数组的变化,可以结合JsonPipe或手动实现深度比较逻辑。
JsonPipe
TypeScript复制
// parent.component.tsimport { Component } from '@angular/core';@Component({ selector: 'app-parent', template: ` <app-child [data]="data"></app-child> <button (click)="updatePrice()">更新价格</button> `,})export class ParentComponent { data = { name: 'xiaoming', age: 12, goods: [ { price: 100 } ] }; updatePrice() { this.data.goods[0].price += 10; // 模拟修改price值 }}
// child.component.tsimport { Component, Input, OnChanges, SimpleChanges } from '@angular/core';import { JsonPipe } from '@angular/common';@Component({ selector: 'app-child', template: ` <div> <p>姓名: {{ data?.name }}</p> <p>年龄: {{ data?.age }}</p> <p>商品价格: {{ data?.goods[0]?.price }}</p> </div> `})export class ChildComponent implements OnChanges { @Input() data: any; ngOnChanges(changes: SimpleChanges) { if (changes['data']) { // 使用JsonPipe进行深度比较 const previousValue = changes['data'].previousValue; const currentValue = changes['data'].currentValue; if (JSON.stringify(previousValue) !== JSON.stringify(currentValue)) { console.log('数据发生了深度变化'); console.log('新数据:', currentValue); } } }}
ngOnChanges:监听@Input()绑定的属性变化。SimpleChanges对象包含当前值和上一次的值。
SimpleChanges
深度比较:由于ngOnChanges默认只能检测对象引用的变化,无法检测对象内部属性的变化,因此需要通过JSON.stringify进行深度比较。
JSON.stringify
JsonPipe:虽然JsonPipe可以将对象转换为字符串,但不建议直接在模板中使用JsonPipe进行逻辑判断,而是在组件逻辑中使用JSON.stringify。
父组件点击按钮后,会修改data.goods[0].price的值。
data.goods[0].price
子组件通过ngOnChanges监听到data的变化,并通过深度比较逻辑检测到price的变化,输出到控制台。
data
price
通过这种方式,子组件可以深度监听父组件传递的复杂数据结构的变化。
登录后可查看更多问答,登录/注册
高仿拼多多WebApp,带你在实战环境中学习Angular
1.2k 4
1.1k 7
977 3
1.8k 4
1.5k 14
购课补贴联系客服咨询优惠详情
慕课网APP您的移动学习伙伴
扫描二维码关注慕课网微信公众号