2016-12-24 56 views
1

我有两个组件:Parent,Child。Parent和Child操作之间的共享值

下面是这种情况:

  • 子从父,其不断改变
  • 孩子总是更新为改变的值
  • 儿童操纵值并显示
  • 得到值在父方面,仅仅因为它在儿童方面被操纵而没有改变该值

一个例子使用案例: enter image description here

我与@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方法还是需要用别的东西吗?

+0

您需要克隆的价值在发送前如果您不希望父母在值为对象时看到孩子所做的更改,请将其发送给孩子。原始值'number','string','boolean',默认情况下被复制。对象通过引用发送。 –

回答

1

Plunker

使用this

新增this变量内部功能,因此question.name变得this.question.name

Primatives

Primatives(字符串,数字,布尔,符号)是更容易,如果你希望子组件所以在父组件我发送的名称属性为子组件的输入字段检测更改工作。

辅元件调节值

有几件事情需要发生以显示子组件操纵值:

  • 创建操纵值的变量,我用manipulatedValue
  • 移动操作逻辑到它自己的功能

这样的:

manipulate() { 
    this.manipulatedValue = "This is the question: " + this.tmpQuestionName; 
} 
  • 调用manipulate功能都ngOnInitngOnChanges

管道内部

如果你需要的是做价值操纵你可能会更好使用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 
    } 
}