【问题标题】:filter() return only the first letter of product selectedfilter() 只返回所选产品的第一个字母
【发布时间】:2019-03-21 23:54:24
【问题描述】:

我从 API 得到两个 JSON:

首先是产品:

 {
        "StatusCode": 0,
        "StatusMessage": "OK",
        "StatusDescription": [
             {
                "s_id": "11E8C70C8A5D78888E6EFA163EBBBC1D",
                "s_serial": "PknGo",
                "active": 0,
              },
             {
                "s_id": "11E8C70FB9D10DB38E6EFA163EBBBC1D",
                "s_serial": "UgnoX",
                "active": 0,
                },
              {
                "s_id": "11E8C7179F85836D8E6EFA163EBBBC1D",
                "s_serial": "IinnM",
                "active": 0,
                }, .....
            {
                "s_id": "11E8C71905123F1A8E6EFA163EBBBC1D",
                "s_serial": "LVncP",
                "active": 0,
             }
              }]
 }

其次,我有这个按产品获得的 JSON: 主页盒p

{
    "StatusCode":0,
    "StatusMessage":"OK",
    "StatusDescription":
    {"products":[
            {
                "s_serial":"PknGo",
                "s_id":"11E8C70C8A5D78888E6EFA163EBBBC1D"
            },
            {
                "s_serial":"LVncP",
                "s_id":"11E8C71905123F1A8E6EFA163EBBBC1D"
            },
            {
                "s_serial":"IinnM",
                "s_id":"11E8C7179F85836D8E6EFA163EBBBC1D"
            }
            ],
                "hb_id":"11E8C71242B742EC8E6EFA163EBBBC1D",
                "active":0,
          }
}

在这部分代码中,我从 API 中获取所有产品,并查找产品和过滤器:

 product: Product;
  products: Product[]=[]

  selectedproducts : string = this.products.filter(
    x => x.s_id === this.product.s_id[0])
    .map(y => y.s_serial).join('');




this.ss.getAllproducts ().subscribe(
      products => {
        this.products = products 
         if (this.products && this.products .length > 0) {
      for (let i = 0; i < this.products .length; i++) {
        let ss = this.products .find(x => {
          let p = this.homeboxp.sensors[i];
          return (p && x.s_id === p.s_id);
        });
        if (ss) {
          this.selectedproducts = ss.s_serial[i];
          console.log(this.selectedproducts )
        }
      }
    }
      });

第一个错误:this.selectedproducts:这仅返回所选产品的第一个字母,而不是所有值。 解决方案

this.selectedproducts = ss.s_serial[i]; to `this.selectedproducts = ss.s_serial;`

第二个错误:EditProductComponent.html:59 错误错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'未定义:n,,'。当前值:'未定义:n,n,n'。 selectedproducts我在html代码中使用过这样的:

<div *ngFor="let sensor of sensorsIdFormArray; let i = index">
    <input formControlName="{{i}}" id="sensors_id" type="text" placeholder="Select Product" [(ngModel)]='selectedproducts'
      aria-label="Number" matInput [matAutocomplete]="auto1">
    <mat-autocomplete autoActiveFirstOption #auto1="matAutocomplete" [displayWith]="displayWith">
      <mat-option (onSelectionChange)="updateForm($event, sensor.s_serial, 's_id', i)"
        *ngFor="let sensor of filteredProducts | async | myPipe: products : 's_serial': i" [value]="sensor.s_id">
        {{sensor.s_serial}}
      </mat-option>
    </mat-autocomplete>
  </div>

我的烟斗:

@Pipe({
    name: 'myPipe'
})
    export class MyPipe implements PipeTransform {
        transform<T>(value: Product, list: T[], field: string, idx: number): T[] {
            const filterValue = value[idx] ? value[idx].toString().toLowerCase() : ''; 
            console.log(filterValue)
            if (filterValue && filterValue.length > 0) {
                return list.filter(sensor => sensor[field].toLowerCase().indexOf(filterValue) === 0);
            }
        }
    }

【问题讨论】:

  • if (ss) { this.selectedproducts = ss.s_serial[i];s_serial 是一个字符串

标签: angular typescript filter autocomplete


【解决方案1】:

文本框无法保存两个值城市名称和城市 ID。但是,如果您的城市名称始终是唯一的,则可以解决此问题。

  1. 获取选定的城市 ID。
  2. 通过城市 id 获取城市名称
  3. 使用城市名称设置 formControl 值
  4. 在屏幕上,让用户添加/删除城市名称
  5. 一旦用户单击“保存/注册”按钮,按城市名称获取 ID 并设置为您发送到服务器的数据。

以下是一些可以帮助你的片段 -

获取城市名称和城市ID的函数

 getCityName(cid) {
    return this.city.find(c => c.city_id == cid).name;
  }

  getCityId(name) {
    return this.city.find(c => c.name == name).city_id;
  }

从现有的城市 ID 初始化表单控件

 city_id: this.client.forEach(x => {

      x.city_id.forEach(cid => {
        //this.formData.push(new FormControl(x.city_id))
        let control = new FormControl(this.getCityName(cid), Validators.required);
        (<FormArray>this.myform.controls['city_id']).push(control);
      });

    })

保存前,将城市名称转换为城市id

onAddprod() {
    let newHbp = this.myform.value;
    let mapped = newHbp.city_id.map(id => this.getCityId(id));
    newHbp.city_id = mapped;
  }

这里是示例演示 - https://stackblitz.com/edit/angular-g2hcvs-bnhugp

【讨论】:

  • 我试试这个,但我的问题是当我在自动完成中使用 [(ngModel)]='selectedproducts' 时。当我有 2 个产品时,在视图中仅显示 3 个不同输入中的第三个产品,而不是 2 个产品。就像帖子中的图片一样
  • 您不能将 Array 绑定到 [(ngModle)]。您需要将其更改为 [(ngModel)]='selectedproducts[i].s_serial'
  • 您正在为每次迭代绑定数组。下一期您将遇到与异步相关的问题。
  • 我试试这个,产品被选中但在视图中不显示,并显示此错误:ERROR TypeError: Cannot read property '0' of undefined at Object.eval [as updateDirectives]
  • 将 if 条件放入 selectedproducts 中。 &lt;div *ngIf="selectedproducts &amp;&amp; selectedproducts.length &gt; 0" *ngFor="let sensor of sensorsIdFormArray; let i = index"&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多