我发现了多个帖子,包括ngSwitchCase in angular 2 instead of ngSwitchWhen,How to bind to '*ngSwitchCase'和Angular 2 - ngSwitchCase。 Google根本没有帮助。
我正在尝试创建一个用于输入搜索条件的简单表格。第一个组件是选择框,第二个组件是输入框。根据您要进行的搜索类型,我想对电子邮件,电话号码等使用不同的输入。
我正在从表单中定义的常量中选择内容。
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}},但它们似乎也不起作用。
所以,我被困住了。请咨询?
答案 0 :(得分:0)
在组件类内部将常量移动为readonly
字段。
在模板中,您只能引用组件类的属性和方法。