答案是不”。在您的示例中,您传递给的值@Input
属性是对对象的引用。如果您有双向绑定,您可以将一个新对象分配给子组件中的该属性:
this.thing = { name: "world", nbm: 10 };
父组件中相应的属性也会相应更新。事实并非如此,正如您所看到的这次堆栈闪电战 https://stackblitz.com/edit/angular-hmkb6n.
但是,由于父组件和子组件具有对同一对象的引用,因此它们都可以修改其属性之一,并且将在另一个组件中观察到该更改。
为了实现双向绑定,可以添加一个@Output
具有相同名称的属性,后跟Change
,并在发生更改时发出事件:
@Input() thing: any;
@Output() thingChange = new EventEmitter();
setNewObject(){
this.thing = { name: "world", nmb: 10 };
this.thingChange.emit(this.thing);
}
如果使用双向绑定语法,则更改将反映到父组件:
<child2 [(thing)]="thing"></child2>
See 这次堆栈闪电战 https://stackblitz.com/edit/angular-elswfz进行演示。
如果你想阻止子组件修改原始对象,你应该绑定对象属性而不是对象本身:
@Input() thingName: string;
@Input() thingNmb: number;
<child [thingName]="thing.name" [thingNmb]="thing.nmb"></child>