Wrong onselect display ? Angular 2+

风格不统一 提交于 2020-01-25 07:25:08

问题


When I select an option instead of showing me the name it shows me the id. That's because I bind [value] = "option.id". I'm sending an id to the server and want to show name.

          <mat-form-field class="example-full-width">
            <input
            matInput
            placeholder="Pretrazite proizvod koji zelite naruciti samo kucajte pocetna slova"
            formControlName="id"
            [matAutocomplete] = "auto"
            >
            <mat-autocomplete #auto="matAutocomplete" >
                  <mat-option *ngFor="let option of allProducts; let i = index"   [value]="option.id"   (onSelectionChange)="getPosts(i)">
                {{ option.name }}
              </mat-option>
            </mat-autocomplete>
          </mat-form-field>



  getProducts() {
    this.product.getAllProducts().subscribe((data: any) => {
     this.allProducts = data.products;
     console.log(data.products);
    });
  }

I also have (onSelectionChange) = "getPosts (i)" function

  getPosts(index){ 
    this.selectedProduct = index;
  }

My question is how do I forward the id and display the name in mat-autocomplete-mat-option options. I suppose this onchange is my function, the problem is that I have dynamic fields Looking my other code

  ngOnInit() {
    this.getProducts();
    this.form = this.fb.group({
      address: [null],
      phone: [null],
      city: [null],
      data: this.fb.array([this.createContact()])
    }); 
    this.contactList = this.form.get('data') as FormArray;
  }

  createContact(): FormGroup {
    return this.fb.group({
      id: [this.selectedProduct], 
      quantity: [null]
    });

In case you need the whole code, ask me, but I didn't want to overwhelm you with a lot of code.


回答1:


You can do something like this, it should help you:

<mat-autocomplete #auto="matAutocomplete" >
              <mat-option *ngFor="let option of allProducts; let i = index"   [value]="selectedProduct.name"   (onSelectionChange)="getPosts(option)">
            {{ option.name }}
          </mat-option>
        </mat-autocomplete>


来源:https://stackoverflow.com/questions/59120701/wrong-onselect-display-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!