【问题标题】:Angular binding ngModel for a Multi Selection List input多选列表输入的角度绑定 ngModel
【发布时间】:2021-07-25 00:44:02
【问题描述】:

我有一个带有大约 100 个输入的角度模板表单。他们中的许多人正在从不同的 mat-selection-lists 中捕获值。我能够绑定到 ngModel 以获取基本输入。但是,多选列表中的值是字符串数组格式。像 ["D", "V"]。后端的 API 需要一个字符串来存储值,我最终使用 JSON.stringify 进行了大量手动转换来存储它,然后使用 str.split(",") 在绑定到元素之前对其进行转换。

Angular 有没有办法自动转换 ngModel 中的数据?有没有办法用 ControlValueAccessor / Directive 做到这一点?

<mat-selection-list   [(ngModel)]="formData.input98">
<mat-list-option value="D">D</mat-list-option>
<mat-list-option value="V">V</mat-list-option>
<mat-list-option value="T">T</mat-list-option>
</mat-selection-list>

【问题讨论】:

    标签: json angular typescript angular-material multi-select


    【解决方案1】:

    Steve,一个带有 ngModel 的 mat-selection-list,但返回一个值数组

    <mat-selection-list #shoes [(ngModel)]="value">
      <mat-list-option *ngFor="let shoe of typesOfShoes" [value]="shoe">
        {{shoe}}
      </mat-list-option>
    </mat-selection-list>
    

    the stackblitz

    更新,所以,一般来说你有一个服务

    list(){
       return this.httpClient.get(...).pipe(
          map((res:any[])=>{
             res.forEach(x=>{
               x.property=x.property.split(",")
             })
             return res;
          })
       )
    
    get(id){
       return this.httpClient.get(...).pipe(
          map((res:any)=>({...res,property=res.property.split(",")}))
       )
    }
    save(data:any){
       const dataCopy={...data,property=data.property.join(",")}
       return this.httpCient.post(....dataCopy)
    }
    

    【讨论】:

    • 谢谢。但是我如何轻松地将它绑定到我的数据库/ api 为字符串/ varchar 类型的字段?无需先将其转换为字符串,反之亦然。
    • 对不起,我喜欢“服务是谁转换从 API 收到的值(我更新了答案)
    【解决方案2】:

    在绑定之前将后端模型映射到视图模型,然后在保存时将其映射回来。

    this.formData = Object.keys(formData).reduce((mappedData, key) => {
      mappedData[key] = formData[key].split(',');
      return mappedData;
    }, {});
    

    在保存时转到另一条路

    saveData = Object.keys(this.formData).reduce((mappedData, key) => {
      mappedData[key] = this.formData[key].join(',');
      return mappedData;
    }, {});
    

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2017-07-02
      • 1970-01-01
      • 2020-05-06
      相关资源
      最近更新 更多