首页 > 解决方案 > 如何将 Angular-Material Select 字段的显示值绑定到 ngModel

问题描述

我对 Angular 开发场景还很陌生,并且从一个简单的出租车预订表开始。我附加了一个带有 2 个属性的数组的 Material-Select 字段,如下所示:

{value: 24, view: '1010 - Vienna'}

效果很好,但是当我提交表单并检查 console.log 字段 zip 等于 24 时。我怎样才能实现,ngModel 绑定到我的下拉列表的视图属性?

非常感谢你!

预期行为:

我想将它包含在 ngForm 创建的 Form 对象中,然后我可以直接将其发送到我的 Express API 以将其存储在数据库中。下面附上图片

图像到表单对象

app.component.html

<form (ngSubmit)="onSubmit(form)" #form="ngForm">

<mat-select placeholder="Postleitzahl" [(ngModel)]="zipValue" name="zip">
    <mat-option *ngFor="let z of zip" [value]="z.value" >{{z.view}} 
    </mat-option>
  </mat-select>

    <button type="submit">submit</button>

</form>

app.component.ts

import { Component, OnInit, OnChanges } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-form-de',
  templateUrl: './form-de.component.html',
  styleUrls: ['./form-de.component.css']
})


export class FormDeComponent {

zip = [
    { view: '1010 - Innere Stadt', value: 24 },
    { view: '1020 - Leopoldstadt', value: 25 },
]

 onSubmit(form: NgForm) {
    console.log(form.value);
  }
}

标签: javascriptangularangular-materialangular-ngmodelangular-forms

解决方案


Make following change in the component - Have a variable zipValue. Set it’s initial value to one of you zip array values [it is also fine to have undefined] -

export class FormDeComponent {

zipValue;

zip = [
    { view: '1010 - Innere Stadt', value: 24 },
    { view: '1020 - Leopoldstadt', value: 25 },
]

ngOnItit() {

}

 onSubmit(form: NgForm) {
    console.log(form.value.zip);
    console.log(this.zipValue);//you should see mat-select selected value; which would be an object.
  }
}

In template make the following change-

EDIT 1 - Use z.view in mat-option like this [This change is for - when you were needed "view" in zip

<mat-option *ngFor="let z of zip" [value]="z.view" >{{z.view}} 
    </mat-option>

EDIT 2 - Use z in mat-option like this [This change is for - when you need both view and value in zip; This is the same as my very first solution]

<mat-option *ngFor="let z of zip" [value]="z" >{{z.view}} 
    </mat-option>

In "Edit 2" on click of button, console.log(form.value.zip); will return {view: '1010 - Innere Stadt', value: 24} which has both value and view. While user will see the "view" in Mat-Select. This is the standard way to implement Mat-Select.

see the following stackblitz - https://stackblitz.com/edit/angular-cvjpxq?file=app/select-overview-example.ts

If you still want form.zip.value to return "1010 - Innere Stadt" and you want "value" then "EDIT 1" is the solution and then you will have to find that object in your zip array like this -

const foundZip = this.zip.find(z => z.view === form.value.zip)

推荐阅读