首页 文章

Angular 2 [typescript]使用json模型从子组件UI更新父组件UI的模型值

提问于
浏览
2

如何将json 'oup' 值从子组件更新为父组件 . 当我尝试将输出事件的子模型中的值更新为父组件时,无效 .

我在下面提供了所有细节

数据处理:

json: [{
      "inp": "hello",
      "oup": "fello"
 }]

父组件

// Parent Component
 @Component({
 selector: 'parent',
 template: `
    <div>Parent sharedVarParent: {{sharedVarParent[0].oup}}
    <input type="text" [ngModel]="sharedVarParent[0].oup"/>
    </div>
    <child [(sharedVar)]="sharedVarParent"></child>

      `,
     directives: [ChildComponent]
 })
 export class ParentComponent {
  sharedVarParent =[{
                     "inp": "hello",
                     "oup": "fello"
                    }]

  constructor() { console.clear(); }
 }

childcomponent

import {Component, EventEmitter, Input, Output} from 'angular2/core'

   // Child Component
  @Component({
    selector: 'child',
    template: `
    <p>Child sharedVar: {{sharedVar[0].oup}}</p>
    <input [ngModel]="sharedVar[0].oup" (ngModelChange)="change($event)">
    `
   })
   export class ChildComponent {
   @Input() sharedVar: string;
   @Output() sharedVarChange = new EventEmitter();
   change(newValue) {
      console.log('newvalue', newValue)
      this.sharedVar = newValue;
      this.sharedVarChange.emit(newValue);
  }
 }

2 回答

  • 2

    这看起来有点奇怪 . 您将 fello 值分配给输入,然后发出更新的值 . 在我看来,你想要发出改变后的 sharedVar

    <input [(ngModel)]="sharedVar[0].oup" (ngModelChange)="change()">
    
    change() {
      this.sharedVarChange.emit(sharedVar);
    }
    
  • 1

    您是否有理由将数组作为输入而不仅仅是字符串发送? plnkr

    your sample有一些奇怪的事情:

    • 你的父输入是一种单向绑定,我不常见并且会给问题增加混乱(fixed)
    <input [(ngModel)]="sharedVarParent[0].oup"/>
    
    • 由于数组是通过引用传递的输入,除非你要创建一个新数组,否则不需要输出你的子组件,只需对你孩子的输入使用双向绑定,它就会更新属性共享数组中的第一个对象(sample)
    <input [(ngModel)]="sharedVar[0].oup">
    
    • 您正在混合传递 sharedVar 数组作为输入,并在更新子文本框值时从 Launcher 输出字符串 . 当发生这种情况时,父对象中的绑定会将 sharedVarParent 更改为字符串,从而弄乱整个事情 . 当父实例化子项时,它将输入 sharedVar 设置为数组 . 当您输入子项的文本框时,它会输出一个字符串,父项将 sharedVarParent 更改为字符串,然后将其作为输入发送给子项 . plnkr

相关问题