首页 > 解决方案 > 在 *ngIf 语句中创建本地数据绑定变量

问题描述

我想从下拉选择元素中传递一个值。在我介绍之前一切正常*ngIf

似乎*ngIf正在从 DOM 中删除#deviceInfoName变量,所以当我去获取它的值时它是未定义的。

<ng-container *ngIf="deviceSelection | async; else deviceManual">
  <mat-form-field>
    <mat-select #deviceInfoName matNativeControl id="apiReadType" placeholder="Device Select">
      <mat-option *ngFor="let device of devices | async" [value]="device.name">{{device.name}}</mat-option>
    </mat-select>
  </mat-form-field>
</ng-container>
<ng-template #deviceManual>
  <mat-form-field class="example-full-width">
    <input matInput #deviceInfoName placeholder="Device" value="">
  </mat-form-field>
</ng-template>

我希望从中提取价值,#deviceInfoName但我得到了Cannot read property 'value' of undefined.

标签: angular

解决方案


我可以创建两个不同的模板,以便它们(click)与变量在同一范围内。这只是很多冗余代码。

  <ng-container *ngIf="deviceSelection | async; else deviceManual">
    <mat-form-field>
      <mat-select #deviceInfoName matNativeControl id="apiReadType" placeholder="Device Select">
        <mat-option *ngFor="let device of devices | async" [value]="device.name">{{device.name}}</mat-option>
      </mat-select>
    </mat-form-field>
    <mat-form-field>
      <mat-select #deviceInfoType matNativeControl id="apiwriteType" placeholder="Info Type">
        <mat-option value="1">Properties</mat-option>
        <mat-option value="2">Attributes</mat-option>
        <mat-option value="3" selected="">Variables</mat-option>
        <mat-option value="4">Structures</mat-option>
        <mat-option value="5">Commands</mat-option>
        <mat-option value="5">Map Descriptions</mat-option>
        <mat-option value="5">RT Status</mat-option>
        <mat-option value="5">Errors</mat-option>
      </mat-select>
    </mat-form-field>
    <button mat-button color="primary" (click)="deviceInfo(deviceInfoName.value, deviceInfoType.value)">Get Info</button>
  </ng-container>
  <ng-template #deviceManual>
    <mat-form-field class="example-full-width">
      <input matInput #deviceInfoName placeholder="Device" value="">
    </mat-form-field>
    <mat-form-field>
      <mat-select #deviceInfoType matNativeControl id="apiwriteType" placeholder="Info Type">
        <mat-option value="1">Properties</mat-option>
        <mat-option value="2">Attributes</mat-option>
        <mat-option value="3" selected="">Variables</mat-option>
        <mat-option value="4">Structures</mat-option>
        <mat-option value="5">Commands</mat-option>
        <mat-option value="5">Map Descriptions</mat-option>
        <mat-option value="5">RT Status</mat-option>
        <mat-option value="5">Errors</mat-option>
      </mat-select>
    </mat-form-field>
    <button mat-button color="primary" (click)="deviceInfo(deviceInfoName.value, deviceInfoType.value)">Get Info</button>
  </ng-template>
</mat-expansion-panel>

推荐阅读