【问题标题】:Two way data binding with object?与对象的两种方式数据绑定?
【发布时间】:2017-12-29 16:31:02
【问题描述】:

我在父组件中有以下内容:

output = {};

在孩子身上我有这个:

 @Input() output: GroupCompnent;
this.output.output = this.gridOptions.api.getSelectedRows();

现在我得到了这个结构:

Object {output: Array(2)}
output Array(2)
[0]:Object
[1]:Object

但我想要这个:

[Object, Object]

有什么建议吗?

我想实现与对象的两种方式数据绑定,因此当我将值更改为要在父项上引用的子项并在父项中获取该数据时。

家长:

  output = {};
   <div *ngIf="visible">
     <z-ag-table [items]="gridOptions" [output]="output"></z-ag-table>
    </div>

孩子:

 @Input() output:GroupComponent;
 selected = () =>  this.output.output = this.gridOptions.api.getSelectedRows();

【问题讨论】:

    标签: angular data-binding


    【解决方案1】:

    您当前得到的输出是完全正确的。您正在向对象output 中的属性output 插入一个数组。似乎您希望 output 实际上是一个数组。所以把output的声明改成parent中的一个数组:

    output = [];
    

    然后在 parent 中,而不是按原样分配值,让我们获取数据,然后将其推送到您的 output 数组。另外你不应该用组件(?)标记@Input()

    @Input() output:GroupComponent;
    

    因为它是一个数组:

    @Input() output: Array<Object> // or if it's a typed array, change it
    

    然后在OnInit 中我们可以获取数组并将内容映射到output 数组:

    ngOnInit() {
      let arr = this.gridOptions.api.getSelectedRows()
      arr.map(x => this.output.push(x))
    }
    

    我们需要这样做以保持 parent outputchild output 之间的引用。

    【讨论】:

      【解决方案2】:

      对于双向数据绑定,您需要在子节点中声明输入和输出,如下所示:

      @Input() output= 0;
      @Output() outputChange = EventEmitter<any>();
      

      请记住,输出事件必须命名为“更改”


      读完cmets后,我建议:

      selected = () =>  { this.output.splice(0); 
           this.output.concat(<your new array>(this.gridOptions.api.getSelectedRows()))
      }
      

      【讨论】:

      • 如果我使用复杂对象,我不需要发出,这是自动绑定的两种方式
      • 好的,我现在看到了问题。可能是您需要 this.output = 而不是 this.output.output =
      • 当我这样做时。输出 = .... 在父级中我没有得到任何东西,我再次得到一个空对象,或者未定义
      • 有什么建议@kimy82?
      • 我想我需要更多代码。你能粘贴父子代码吗?
      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多