網站搜尋

angular - angular2 訪問模板變數的值,


我想了解如何在模板中訪問已選項目的值。具體來說,我想知道如何在模板中訪問 IPMIDisplayTime 和 IPMIDisplayTime 的已選值,並在後續使用它們。

 import {ViewChild, ElementRef} from '@angular/core';

@Component({
  selector: 'app-select-dialog',
  template:`<h1 mat-dialog-title>
  {{ title | translate }}
</h1>
<div mat-dialog-content>
  <mat-select  #IPMIDisplayTime name="name" placeholder="optionPlaceHolder" [(ngModel)]="IPMIDisplayTimeSelection">
      <mat-option *ngFor="let option of options" [value]="options.value">
          {{ option.label }}
      </mat-option>
  </mat-select>  
</div>
<div mat-dialog-actions>
  &nbsp;
  <span fxFlex></span>
  <button class="mat-raised-button mat-accent" (click)="dialogRef.close(false)">{{"Close" | translate}}</button>
  <span fxFlex></span>
  <button class="mat-raised-button mat-accent" (click)="dialogRef.close(true)">{{"OK" | translate}}</button> 
</div>`,
  styleUrls : [ './select-dialog.component.scss' ]
})
export class SelectDialogComponent {

  public title: string;
  public options: Array<{ label: string, value: string }>;
  public optionPlaceHolder: string;
  public method: string;
  public params: string;
  @ViewChild('IPMIDisplayTime') IPMIDisplayTimeSelect: ElementRef;
  IPMIDisplayTimeSelection: string;


  constructor(public dialogRef: MatDialogRef < SelectDialogComponent >, protected translate: TranslateService ) {

  }





}

答案#1

您在 <mat-select> 元件上使用了 [(ngModel)] 雙向綁定。這意味著 IPMIDisplayTimeSelection 將始終與當前的 <mat-select> 值匹配。

你不需要使用 @ViewChild 裝飾器和 #IPMIDisplayTime 模板變數。

someFn() {
  // this is the value of your select component
  console.log(this.IPMIDisplayTimeSelection);
}