【问题标题】:how to properly bind loaded data to @ng-select, angular5如何正确地将加载的数据绑定到@ng-select,angular5
【发布时间】:2018-09-05 03:27:09
【问题描述】:

使用 angular 5 和 @ng-select 我发现了一些绑定到先前选择的数据的问题(在编辑表单中)

Ngselect 定义

 <ng-select
     [items]="contenedores$ | async"
     bindLabel="numero"
     bindValue="id"
     [(ngModel)]="embarqueContenedor.contenedor"> 
 </ng-select>

从 api 我以这种方式序列化实体:

从服务器(json)接收(这是来自模型)

{
    "id": 1,
    "numero": "dsvsd",
    "dimension": 234,
    "tipoContenedor": "324",
    "contenedorEmbarques": [],
    "text": "dsvsd",
    "value": 1,
    "name": "dsvsd",
    "createdAt": "2018-03-26T12:44:48-04:00",
    "updatedAt": "2018-03-26T12:44:48-04:00"
}

我还用这些项目填充 ngselect。我从服务器收到了一个包含上述对象的数组(实际上是同一个实体,因此它们以相同的方式序列化)

this docthis one 之后,我尝试使用两者,所以我添加了一些额外的序列化字段(ummaped)并得到了上面的 json(text=name=numero,id=value)。问题是它根本不起作用,每次我有一个选定的选项时,仍然会从 ng-select.js 收到这个错误:

绑定 object({"id":2,"numero":"dfdhdf","dimension":324234,"tipoContenedor":"324324","contenedorEmbarques":[],"text":"dfdhdf","name": "dfdhdf","value":2,"createdAt":"2018-03-26T12:44:48-04:00","updatedAt":"2018-03-26T12:44:48-04:00"} ) 不允许使用 bindValue。

对象具有相同和必需的属性,但仍然不起作用

有什么帮助吗?

【问题讨论】:

    标签: angular data-binding angular5 angular-ngselect


    【解决方案1】:

    这一行是他们验证您的支持值是否有效的方式:

        const validateBinding = (item: any): boolean => {
            if (isObject(item) && this.bindValue) {
                this._console.warn(`Binding object(${JSON.stringify(item)}) with bindValue is not allowed.`);
                return false;
            }
            return true;
        };
    

    这就是您的错误的来源。我猜这行:

    [(ngModel)]="embarqueContenedor.contenedor"

    搞砸了,因为ngModel 指向一个对象而不是id 每个bindValue

    试试:

    [(ngModel)]="embarqueContenedor?.contenedor?.id"
    

    【讨论】:

    • 完成但正如预期的那样只更新每个选择的 id 属性而不是引用。所以当我提交时,我只是在更改数据库上的 id 并引发异常。还是谢谢
    【解决方案2】:

    我有一个更简单的例子,有一个具有这种格式的对象数组

    {name: 'en'}
    

    ng-select 声明:

     <ng-select [items]="sourceLanguages"
                     [(ngModel)]="sourceSelection"
                     bindValue="name"
                     bindLabel="name"
                     [clearable]="false"
                     [searchable]="false"                  
    
          >
    

    要在字符串数组arr = ['en', 'fr', 'de'] 上获得默认选择,我只需要输入this.sourceSelection = arr[1]; 非常类似于上面的答案:要获得默认选择,您需要添加一个属性而不是整个对象。 它对我有用,但你的例子显然更复杂......

    【讨论】:

      【解决方案3】:

      当使用带有 ng-select 的 ngModel 时,您必须传递所选值的 id,如下例所示:

      <ng-select [items]="countries"
             bindLabel="nested.name"
             bindValue="nested.countryId"
             placeholder="Select value"
             [(ngModel)]="selectedCountryId">
      </ng-select>
      

      对于多选传递的 id 数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        • 1970-01-01
        • 2012-12-24
        • 2021-07-10
        • 2017-08-23
        • 1970-01-01
        • 2015-11-10
        相关资源
        最近更新 更多