【问题标题】:How to get Id of selected value in Mat-Select Option in Angular 5如何在 Angular 5 的 Mat-Select 选项中获取所选值的 ID
【发布时间】:2018-07-20 04:58:58
【问题描述】:

如何在 mat-select angular 5 中获取所选选项值的 id。在 onchangeevent 中仅获取所选选项的值。但是如何获取所选选项值的 id。

 client.component.html
<mat-form-field>
    <mat-select placeholder="Client*" #clientValue  (change)="changeClient($event)">
    <mat-option  *ngFor="let client of clientDetails"   [value]="client.clientName">
      {{client.clientName |  json}}
    </mat-option>
  </mat-select>
</mat-form-field>

client.component.ts file
export class Client{
     changeClient(event){
     console.log(event);
 }
}

【问题讨论】:

    标签: angular angular-material-5


    【解决方案1】:

    这个问题是 Angular 5 特有的,但对于其他使用更新版本的 Angular 的人来说,(change) 事件不适用于 mat-select。

    Angular 6 中,(change) 事件已更改为 (selectionChange)

    原来是这样:

    <mat-form-field>
        <mat-select placeholder="Client*" #clientValue  (selectionChange)="changeClient($event.value)">
        <mat-option  *ngFor="let client of clientDetails" [value]="client.id">
          {{client.clientName}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    在组件中:

    changeClient(value) {
        console.log(value);
    }
    

    来自this answerthe documentation

    【讨论】:

    • 在 Angular 8 中,它与 (selectionChange) 一起使用。谢谢
    【解决方案2】:

    组件 => app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    import { MaterialDropDown, PAYMENT_MODES } from './order.model';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    
    export class AppComponent implements OnInit {
      name = 'Angular';
      sampleForm: FormGroup;
      paymentModes: MaterialDropDown[];
      constructor() {}
    
      ngOnInit() {
        this.paymentModes = PAYMENT_MODES;
        this.sampleForm = new FormGroup({
          payment_mode: new FormControl(null, Validators.required),
        });
      }
    
      get f() {
        return this.sampleForm.controls;
      }
    
      onPaymentSelection() {
        console.log(this.sampleForm.value.payment_mode);
      }
    
      onSubmit() {
        console.log(this.sampleForm.value);
      }
    }
    

    模块 => app.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    
    import { AppComponent } from './app.component';
    import { HelloComponent } from './hello.component';
    import { MatFormFieldModule } from '@angular/material/form-field';
    import { MatSelectModule } from '@angular/material/select';
    import { MatButtonModule } from '@angular/material/button';
    @NgModule({
      imports: [ 
        BrowserModule, 
        BrowserAnimationsModule,
        FormsModule, 
        ReactiveFormsModule, 
        MatFormFieldModule, 
        MatSelectModule,
        MatButtonModule
        ],
      declarations: [ AppComponent, HelloComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    模型 => order.model.ts

    export interface MaterialDropDown {
        value: string;
        viewValue: string;
    }
    
    export const PAYMENT_MODES: MaterialDropDown[] = [
        { value: 'Cash', viewValue: 'Cash' },
        { value: 'cheque', viewValue: 'Cheque' },
        { value: 'dd', viewValue: 'Demand Draft' },
        { value: 'neft', viewValue: 'NEFT' },
        { value: 'rtgs', viewValue: 'RTGS' },
        { value: 'upi', viewValue: 'UPI' }
    ];
    

    查看 => app.component.html

    <form [formGroup]="sampleForm" (ngSubmit)="onSubmit()">
        <mat-form-field>
            <mat-label>Payment Mode</mat-label>
            <mat-select formControlName="payment_mode" (ngModelChange)="onPaymentSelection($event)">
                <mat-option *ngFor="let payment_mode of paymentModes" [value]="payment_mode.value">
                    {{ payment_mode.viewValue }}
                </mat-option>
            </mat-select>
            <mat-hint *ngIf="!f.touched">Please select a valid Payment Mode.</mat-hint>
            <div *ngIf="!f.payment_mode.valid && f.payment_mode.touched">
                <mat-error *ngIf="f.payment_mode.errors.required">Payment Mode field is required</mat-error>
            </div>
        </mat-form-field>
      <button type="submit" mat-raised-button color="primary" [disabled]="sampleForm.invalid">Save</button>
    </form>
    <p style="color: #f00">Check Console for outputs</p>
    

    CSS => app.component.css

    mat-form-field { width: 280px; margin-right: 35px}
    

    WORKING DEMO

    【讨论】:

      【解决方案3】:

      您还可以订阅mat-select的值更改 通过使用ViewChild 装饰器和ngAfterViewInit 更少'html-intrusive'。

      这是一个例子:

      [HTML]

      <mat-form-field [floatLabel]="auto">
          <mat-label>Type</mat-label>
              <mat-select #matSelect required> //the #matSelect is important here
                  <mat-option *ngFor="let type of types" [value]="type.value">
                      {{type.viewValue}}
                  </mat-option>
          </mat-select>
      </mat-form-field>
      

      [TS]

       import { Component, ViewChild, AfterViewInit } from '@angular/core';
       import { MatSelect } from '@angular/material';
      
       @Component({
              selector: 'app-export-security-pack-material',
              templateUrl: './export-security-pack-material.component.html',
              styleUrls: ['./export-security-pack-material.component.scss']
       })
      
       export class ExportSecurityPackMaterialComponent implements AfterViewInit {
      
          constructor() {}
      
          types: Object[] = [
              { value: 'example-value-0', viewValue: 'ExampleViewValue0' 
              },
              { value: 'example-value-1', viewValue: 'ExampleViewValue1' }
          ];
      
          @ViewChild('matSelect') matSelect: MatSelect;
             //Reference Variable //variable Name //Type
      
          ngAfterViewInit() {
              this.matSelect.valueChange.subscribe(value => {
                  console.log(value);
              });
          }
       }
      

      每次更改选择器值时,您的值都应记录在开发控制台Ctrl+Shift+IF12 中。

      或者,如果您不需要 onchange,您可以直接这样做:

      [HTML]

      <mat-form-field [floatLabel]="auto">
          <mat-label>Type</mat-label>
              <mat-select [(value)]="matSelectValue" required> <---
                  <mat-option *ngFor="let type of types" [value]="type.value">
                      {{type.viewValue}}
                  </mat-option>
          </mat-select>
      </mat-form-field>
      

      【讨论】:

        【解决方案4】:

        为此,您需要:

        (change)="changeClient($event)" 更改为(change)="changeClient($event.value)"

        [value]="client.clientName"[value]="client.id"

        <mat-form-field>
            <mat-select placeholder="Client*" #clientValue  (change)="changeClient($event.value)">
            <mat-option  *ngFor="let client of clientDetails"   [value]="client.id">
              {{client.clientName}}
            </mat-option>
          </mat-select>
        </mat-form-field>
        

        WORKING DEMO

        【讨论】:

        • 但我需要 changeclient 事件中的值和 id。对于那个 [value]="client.id+,+client.value" 和 changeClient($event.value) ...这是我可以获得价值的方式或任何其他方式来获得它
        • 明白但如何从 mat-select 中获取选定的索引?
        • @KT ,在工作演示中changeClient2 正在获取所选项目的索引,请检查
        • @VivekDoshi........你能帮我解决这个问题吗..?
        • 哦,我很抱歉.. 错过了添加链接......stackoverflow.com/questions/52188340/….. 请看看
        猜你喜欢
        • 2018-11-15
        • 2019-08-07
        • 2020-11-29
        • 2011-08-10
        • 2021-01-16
        • 2021-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多