Angular *ngSwitchCase 没有执行
Angular *ngSwitchCase is not executing
我是 Angular 的新手。我在我的程序中使用 ngSwitch
,但每次我 运行 时,程序 *ngSwitchDefault
执行而不是 *ngSwitchCase
。这是代码:
<select [(ngModel)]="selectedControl" class="form-control">
<option *ngFor="let inputControl of inputArray; let i=index"
[value]="inputControl">{{inputArray[i]}}</option>
</select>
<span [ngSwitch]="selectedControl">
<span *ngSwitchCase="text">
<p>text is selected</p>
</span>
<span *ngSwitchCase="radio">
<p>radio is selected</p>
</span>
<span *ngSwitchDefault>
<p>Default value</p>
</span>
</span>
将 *ngSwitchCase
表达式包装到 ''
中,使它们成为 strings
。比较将与 ===
一起使用,因此它会将 string
与 string
进行比较。在您的情况下,它将找到名称为 radio
或 text
的成员并获取其未定义的值。
<span [ngSwitch]="selectedControl">
<span *ngSwitchCase="'text'">
<!-- ^----^ -->
<p>text is selected</p>
</span>
<span *ngSwitchCase="'radio'">
<!-- ^-----^ -->
<p>radio is selected</p>
</span>
<span *ngSwitchDefault>
<p>Default value</p>
</span>
</span>
根据 https://angular.io/api/common/NgSwitchCase ngSwitchCase
预期 expression
而不是 string
。
如果您想使用硬编码字符串,请将 *ngSwitchCase="text"
替换为 *ngSwitchCase="'text'"
Unlike JavaScript, which uses strict equality, Angular uses loose
equality. This means that the empty string, "" matches 0.
我是 Angular 的新手。我在我的程序中使用 ngSwitch
,但每次我 运行 时,程序 *ngSwitchDefault
执行而不是 *ngSwitchCase
。这是代码:
<select [(ngModel)]="selectedControl" class="form-control">
<option *ngFor="let inputControl of inputArray; let i=index"
[value]="inputControl">{{inputArray[i]}}</option>
</select>
<span [ngSwitch]="selectedControl">
<span *ngSwitchCase="text">
<p>text is selected</p>
</span>
<span *ngSwitchCase="radio">
<p>radio is selected</p>
</span>
<span *ngSwitchDefault>
<p>Default value</p>
</span>
</span>
将 *ngSwitchCase
表达式包装到 ''
中,使它们成为 strings
。比较将与 ===
一起使用,因此它会将 string
与 string
进行比较。在您的情况下,它将找到名称为 radio
或 text
的成员并获取其未定义的值。
<span [ngSwitch]="selectedControl">
<span *ngSwitchCase="'text'">
<!-- ^----^ -->
<p>text is selected</p>
</span>
<span *ngSwitchCase="'radio'">
<!-- ^-----^ -->
<p>radio is selected</p>
</span>
<span *ngSwitchDefault>
<p>Default value</p>
</span>
</span>
根据 https://angular.io/api/common/NgSwitchCase ngSwitchCase
预期 expression
而不是 string
。
如果您想使用硬编码字符串,请将 *ngSwitchCase="text"
替换为 *ngSwitchCase="'text'"
Unlike JavaScript, which uses strict equality, Angular uses loose equality. This means that the empty string, "" matches 0.