如何在 ngSwitchCase 中使用常量

How to use constants with ngSwitchCase

我发现了多个帖子,包括 , How to bind to '*ngSwitchCase', and 。 Google 一点帮助也没有。

我正在尝试创建一个用于输入搜索条件的简单表单。第一个组件是 select 框,第二个组件是输入框。根据您正在进行的搜索类型,我想对电子邮件、phone 号码等使用不同的输入

我正在从我的表单中定义的常量中获取 select。

const SEARCH_BY_EMAIL = 'email';
const SEARCH_BY_PHONE = 'phone';
const SEARCH_BY_POSTAL_CODE = 'postalCode';

@Component({
  selector: 'app-choose-search-criteria',
  templateUrl: './choose-search-criteria.component.html',
  styleUrls: ['./choose-search-criteria.component.css']
})
export class ChooseSearchCriteriaComponent implements OnInit {

  searchTypes = [
      {value: SEARCH_BY_EMAIL, label: 'Email'},
      {value: SEARCH_BY_PHONE, label: 'Phone Number'},
      {value: SEARCH_BY_POSTAL_CODE, label: 'Zip Code'}
    ];
  searchBy: string;
  searchValue = '';

  constructor(protected dialogRef: MatDialogRef<ChooseSearchCriteriaComponent>,
              @Inject(MAT_DIALOG_DATA) public data: ChooseCriteriaDialogData) { }

  ngOnInit() {
  }

}

<h2>Enter Search Values</h2>
<div class="formFields">
  <mat-form-field>
    <mat-label>Search By</mat-label>
    <mat-select [(value)]="searchBy">
      <mat-option *ngFor="let searchType of searchTypes" [value]="searchType.value">
        {{searchType.label}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <div [ngSwitch]="searchBy">
    <mat-form-field *ngSwitchCase="SEARCH_BY_EMAIL">
      <input matInput placeholder="Enter Email Address" type="email" [(ngModel)]="searchValue"/>
    </mat-form-field>
    <mat-form-field *ngSwitchCase="SEARCH_BY_PHONE">
      <input matInput placeholder="Enter Phone Number" type="number" [(ngModel)]="searchValue"/>
    </mat-form-field>
    <mat-form-field *ngSwitchCase="SEARCH_BY_POSTAL_CODE">
      <input matInput placeholder="Enter Zip Code" type="number" [(ngModel)]="searchValue"/>
    </mat-form-field>

    <p *ngSwitchDefault>Select how you wish to search.</p>
  </div>
</div>

问题是它似乎没有在 ngSwitchCase 上找到我的常量。我也试过 {SEARCH_BY_POSTAL_CODE} 和 {{SEARCH_BY_POSTAL_CODE}} 但这些似乎也不起作用。

所以,我卡住了。请指教?

将组件 class 内的常量作为 readonly 字段移动。

从模板中您只能引用组件的属性和方法class。