首页 > 解决方案 > 单击事件返回未定义。为什么?

问题描述

我正在尝试传递从 mat-option 选项之一中获取的日期,但是当在 mat-option 标签中时,我将 click 方法与事件一起打印并打印它返回的事件undefined!我该怎么做才能解决?

HTML

    <mat-drawer-content class="Font">
      <mat-form-field appearance="fill">
        <mat-label>choose the date
        </mat-label>
        <mat-select [(value)]="selected">
          <mat-option value="option1" (click)="onclick($event)">{{this.shareDate.newCurrentDate}}</mat-option>
          <mat-option value="option2" (click)="onclick($event)">{{this.shareDate.newTomorrow}}</mat-option>
        </mat-select>
      </mat-form-field>
      <mat-form-field >
        <mat-label>choose the time
        </mat-label>
        <mat-select #hasBackdrop>
          <mat-option [value]="false" *ngFor="let time of dayaHours">
            <div class="hourTime">{{formatTime(time.time)}}</div>
          </mat-option>
        </mat-select>
      </mat-form-field>
    </mat-drawer-content>
  </mat-drawer-container>

TS

onclick(event) {
  console.log(event.value); // undefined
}

标签: typescriptangular-materialangular8

解决方案


你想做的事情是不可能的,因为点击事件没有任何价值。替代方案我建议您执行以下操作:

<mat-option #matOption1 (click)="onClick(matOption1.value)" [value]="'GB'">Great Britain</mat-option>

我也创建了一个Stackblitz

有关更多信息,您可以阅读:https ://angular.io/guide/template-reference-variables


推荐阅读