角度-使用箭头功能以两种方式绑定对象属性 [英] Angular - Using arrow functions to two way bind object properties

查看:47
本文介绍了角度-使用箭头功能以两种方式绑定对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有效.它遍历一个对象数组以获得每行一个,然后针对每个对象遍历一个数组定义每个列应显示的内容.

The following code works. It loops over an array of objects to get one per row and then for every object it loops over an array defining what should be displayed per column.

 <tr  *ngFor="let object of objects"
   <td *ngFor="let column of tableColumns;" > 
     {{column.attribute(object)}} //Explained bellow
   </td>
 </tr>

column.attribute是箭头功能,即object => object.a.property.建议在此处提出解决方案用于访问插值中嵌套对象的属性.

The column.attribute is an arrow function i.e. object => object.a.property. This solution was suggested here and is used to access properties of nested objects in interpolation.

当我想使用这种方式以两种方式盒装香蕉"数据绑定访问属性时,就会出现问题.

The problem arises when I want to use this way of accessing the properties in a two way "banana in a box" data binding.

无效不起作用:

<input type="text" [(ngModel)]="column.attribute(object)">

经过一些试验,我发现了一种解决方法,但是它不是那么优雅,因此就问是否可以很好地编写这个问题.

After some experimentation I found a workaround but it is not so elegant and thus the question if this can be written nicely.

我这样写了两种方式的数据绑定:

I wrote the two way data binding like this:

<input [value]="column.attribute(object)"(input)="onInput($event, column, object)">

input事件上调用的方法:

private onInput(event, column, object){
        column.attribute(object, event.target.value);
    }

真正糟糕的是,我的attribute方法不再是上述的箭头功能,而是普通的丑陋功能.

and the really bad part is that my attributes method is no longer an arrow function as above, but a normal ugly one.

private editPhone(user, newValue = undefined){
    if (newValue != undefined) {
      user.phone = newValue;
    }
    return user.phone
  }

推荐答案

箭头功能允许从对象中读取值.如果要将新值写入对象,则需要另一个函数,将新值存储在对象中:

The arrow function allows reading the value from the object. If you want to write a new value into the object, you need another function, taking the new value and storing it in the object:

<input [ngModel]="column.attribute(object)" (ngModelChange)="column.write(object, $event)" />

当然,您也可以使用单个函数同时充当读者和作家,就像您在问题中使用editPhone函数所做的那样.

Of course, you can also use a single function acting both as a reader and as a writer, as you're doing in your question with your editPhone function.

此功能可以完美地编写为箭头功能:

This function can perfectly be written as an arrow function:

(user, newValue) => {
  if (newValue !== undefined) {
    user.phone = newValue;
  }
  return user.phone;
}

这篇关于角度-使用箭头功能以两种方式绑定对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆