我有两个组成部分:Parent,Child。
以下是该方案:
我已经用@Input尝试了这个。因为@Input值在Child侧被操纵,所以在Parent侧也会改变。这是我想要阻止的,但仍然希望继续从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方法执行此操作,还是需要使用其他内容?
答案 0 :(得分:1)
this
为函数内的变量添加了this
,因此question.name
变为this.question.name
。
Primatives(String,Number,Boolean,Symbol)更容易使用,如果您希望子组件检测到更改,那么在父组件中我将name属性发送到子组件的输入字段。
在子组件中显示受控值时需要做一些事情:
manipulatedValue
。manipulate() {
this.manipulatedValue = "This is the question: " + this.tmpQuestionName;
}
manipulate
和ngOnInit
ngOnChanges
功能
如果您只需要进行价值操作,那么最好使用pipe
@Component({
selector: 'c-parent',
template: `
<div>Parent Question Name: {{question.name}}</div>
<button type="button" label="xxx" (click)="changeTheValue()">Change the value</button>
<br/>
<c-child [tmpQuestionName]="question.name"></c-child>`
})
export class Parent implements OnInit {
question = { name: '1' };
ngOnInit() {
this.question.name = "1";
}
changeTheValue(){
this.question.name = 'new ' + this.question.name;
}
}
@Component({
selector: 'c-child',
template: `<div>Child Manipulated Value: {{manipulatedValue}}</div>`
})
export class Child implements OnChanges, OnInit {
@Input() tmpQuestionName; // be updated for the changes
manipulatedValue;
ngOnInit() {
this.manipulate();
}
ngOnChanges() {
this.manipulate();
}
manipulate() {
this.manipulatedValue = "This is the question: " + this.tmpQuestionName; //manipulate the value
}
}