angular - 如何在 ngSwitchCase 中使用常量
问题描述
我发现了多个帖子,包括ngSwitchCase in angular 2 而不是 ngSwitchWhen、如何绑定到 '*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}} 但这些似乎也不起作用。
所以,我被困住了。请给点建议好吗?
解决方案
将组件类内的常量作为readonly
字段移动。
从模板中,您只能引用组件类的属性和方法。
推荐阅读
- vb.net - 如何在 WPF VB 中正确设置 BackgroundWorker
- sql - 在标准 SQL 上查找数组位置
- python - 使用单个 plt.bar() 函数设置条形图标签和值
- python - 从列表的每个元素中获取子字符串
- java - 如何使用 Scanner 函数接受多个输入以及满足 if 语句的输入?
- reactjs - 反应:CheckBox 以编程方式检查状态不反映复选框状态
- python - 如何在 Windows 10 下定期在某些 conda 环境中运行 python 脚本?
- python - 如何在使用 functools.wraps 并保留对装饰实例的访问时创建一个带参数的装饰器类
- c# - Docker for Windows 与 Kubernetes 和 Windows 容器
- javascript - 如何修复 BeagleBone Black 服务文件自动启动脚本错误,状态 = 203/EXEC