-
Notifications
You must be signed in to change notification settings - Fork 27.1k
ngSwitchCase doesn't handle undefined properly #33873
Description
🐞 bug report
Affected Package
The issue is caused by package @angular/common
Is this a regression?
No
Description
It's currently impossible to use the type system to forbid invalid states. An example for that would be:
{
isLoadingProject: boolean
project?: Project | null
}
would result in 6 possible configurations, of which only 3 would be a valid state. To handle that case better, the following is possible
{
project?: Project | null
}
Using ngSwitch however, there is currently no distinction to make between undefined (still loading) and null (not found) and hence, the following template always shows both the loader and the not found method if the value of project is null
<ng-container [ngSwitch]="project">
<div *ngSwitchCase="undefined">
Loading project
</div>
<div *ngSwitchCase="null">
Project not found!
</div>
<div *ngSwitchDefault>
{{ project | json }}
</div>
</ng-container>
This is because ngSwitch uses == and not ===, while in javascript
null == undefined // true
null === undefined // false
The line in question is https://github.com/angular/angular/blob/8.2.14/packages/common/src/directives/ng_switch.ts#L135 and changing it makes it work properly and helps me handle all those invalid states with this simple approach.
🔬 Minimal Reproduction
https://stackblitz.com/edit/angular-wqgssr
This stackblitz goes through all three valid states,
- undefined (loading)
- an object (loaded project)
- null (not found)
What to look for: The loading and not found messages are both shown at the same time for undefined and null cases.
🌍 Your Environment
Angular Version:
Angular CLI: 9.0.0-rc.2
Node: 12.13.0
OS: darwin x64
Angular: 9.0.0-rc.2
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.900.0-rc.2
@angular-devkit/build-angular 0.900.0-rc.2
@angular-devkit/build-optimizer 0.900.0-rc.2
@angular-devkit/build-webpack 0.900.0-rc.2
@angular-devkit/core 9.0.0-rc.2
@angular-devkit/schematics 9.0.0-rc.2
@ngtools/webpack 9.0.0-rc.2
@schematics/angular 9.0.0-rc.2
@schematics/update 0.900.0-rc.2
rxjs 6.5.3
typescript 3.6.4
webpack 4.41.2