在* ngIf语句中创建本地数据绑定变量

时间:2018-12-22 14:04:47

标签: angular

我想从下拉选择元素中传递一个值。在介绍*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

1 个答案:

答案 0 :(得分:0)

我可以创建两个不同的模板,以使(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>