在 Angular 中,组件的输入属性(Input)默认是单向绑定的,即父组件可以向子组件传递数据,但子组件不能直接修改父组件传递过来的数据。如果想要实现多实例组件的输入属性的双向绑定,可以使用 Angular 的双向绑定语法以及利用 @Input
和 @Output
装饰器。
下面是一个示例代码,演示了如何解决多实例组件的输入属性双向绑定问题:
child.component.ts
:import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent {
@Input() inputValue: string;
@Output() inputValueChange: EventEmitter = new EventEmitter();
onInputChange() {
this.inputValueChange.emit(this.inputValue);
}
onButtonClick() {
// 子组件可以修改输入属性值
this.inputValue = '修改后的值';
this.inputValueChange.emit(this.inputValue);
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
value = '初始值';
// 父组件可以监听到子组件输入属性值的变化
onInputChange(newValue: string) {
console.log('新的输入属性值:', newValue);
}
}
在上述代码中,子组件中的 [(ngModel)]
是 Angular 的双向绑定语法,用于实现输入属性的双向绑定。同时,通过 @Input
和 @Output
装饰器,将输入属性和输出属性绑定到了 inputValue
和 inputValueChange
属性上。父组件中的 [(inputValue)]="value"
语法实现了对子组件 inputValue
输入属性的双向绑定。
通过这种方式,可以实现多实例组件的输入属性双向绑定,父组件能够监听到子组件输入属性值的变化,并且子组件也可以修改输入属性值。