【问题标题】:How to use constants with ngSwitchCase如何在 ngSwitchCase 中使用常量
【发布时间】:2019-06-14 13:52:12
【问题描述】:

我找到了多个帖子,包括 ngSwitchCase in angular 2 instead of ngSwitchWhenHow to bind to '*ngSwitchCase'Angular 2 - ngSwitchCase。谷歌一点帮助都没有。

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

我从表单中定义的常量中选择。

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}} 但这些似乎也不起作用。

所以,我被困住了。请给个建议?

【问题讨论】:

  • 尝试在组件类中移动const 声明。
  • @ConnorsFan 就是这样,但接受的答案包括我以前从未使用过的只读部分。感谢您的帮助。

标签: angular angular-material ng-switch


【解决方案1】:

将组件类中的常量作为readonly 字段移动。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2010-12-16
    • 2016-09-09
    相关资源
    最近更新 更多