1
我有两个组件:Parent,Child。Parent和Child操作之间的共享值
下面是这种情况:
- 子从父,其不断改变
- 孩子总是更新为改变的值
- 儿童操纵值并显示
- 得到值在父方面,仅仅因为它在儿童方面被操纵而没有改变该值
我与@input尝试这样做。因为@Input值在Child方面被操纵,所以在Parent方面它也会改变。这是我想要阻止的,但仍然想要继续从父端获取更新的值。
一个例子代码@input:
@Component({
selector: 'c-parent',
template: `
<div>{{question.name}}</div>
<button type="button" label="xxx" (click)="changeTheValue()"></button>
<br/>
<c-child [tmpQuestion]="question"></c-child>`
})
export class Parent implements OnInit {
question: Question; // don't get changed from the Child side
ngOnInit() {
question.name = "1";
}
changeTheValue(){
question.name = "2";
}
}
@Component({
selector: 'c-child',
template: `<div>{{tmpQuestion.name}}</div>`
})
export class Child implements OnInit {
@Input() tmpQuestion: Question; // be updated for the changes
ngOnInit() {
tmpQuestion.name = "This is the question: " + question.name; //manipulate the value
}
}
我怎样才能做到这一点与@input方法还是需要用别的东西吗?
您需要克隆的价值在发送前如果您不希望父母在值为对象时看到孩子所做的更改,请将其发送给孩子。原始值'number','string','boolean',默认情况下被复制。对象通过引用发送。 –