在Angular中,如果子组件更改了通过Input()传递的值,父组件不会自动收到更新的通知。但是,我们可以使用以下两种方法来解决这个问题:
下面是一个示例代码:
子组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent {
@Input() value: string;
@Output() valueChange: EventEmitter = new EventEmitter();
changeValue() {
this.value = 'New Value';
this.valueChange.emit(this.value);
}
}
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Parent Value: {{ parentValue }}
`
})
export class ParentComponent {
parentValue = 'Initial Value';
onChildValueChange(newValue: string) {
this.parentValue = newValue;
}
}
下面是一个示例代码:
子组件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent {
@Input() value: string;
changeValue() {
this.value = 'New Value';
}
}
父组件:
import { Component, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Parent Value: {{ parentValue }}
`
})
export class ParentComponent implements OnChanges {
parentValue = 'Initial Value';
ngOnChanges(changes: SimpleChanges) {
if (changes.parentValue && !changes.parentValue.firstChange) {
this.parentValue = changes.parentValue.currentValue;
}
}
}
以上是两种解决子组件更改Input()不会通知父组件已更新的方法,根据实际需求选择适合的方法来解决问题。