一、ngSwitchCase
当我们用到switch...case时,我们会需要在满足两个或多个不同条件时做同样的操作,在js或其他一些语言中,可以像下面代码这样去实现
switch(type){
case condition1:
case condition2:
//do anything
break;
case condition3:
//do something
break;
default:
//do something
}
现在我需要用ngSwitchCase做类似的事,但是我发现我不能在同一个标签上去写两个ngSwitchCase,也不能在ngSwitchCase上绑定多值,一种比较糟糕的做法就是我不得不像下面这样去实现
<div [ngSwitch]="type">
<div *ngSwitchCase="condition1">From1</div>
<div *ngSwitchCase="condition2">From1</div>
<div *ngSwitchCase="condition3">From2</div>
<div *ngSwitchDefault>From3</div>
</div>
条件1和条件2要渲染的内容相同,但我不得不用两个容器分别包裹。
尝试多次,终于在two-switch-case-values找到一种比较优雅的做法
<div [ngSwitch]="type">
<div *ngSwitchCase="type === condition1 || type === condition2 ? type : false">From1</div>
<div *ngSwitchCase="condition3">From2</div>
<div *ngSwitchDefault>From3</div>
</div>
在two-switch-case-values可参与更多讨论,若有更多建议欢迎在下方评论。
二、ngClass
我尝试使用多个类名,并且其中一个类名是变化的
<div [ngClass]="'pre' + variable {'otherclass': condition}"></div>
像上面这样仅仅使用ngClass总是报错。
正确的写法是
<div [class]="'pre'+ variable" [ngClass]="{otherClass: condition}"></div>
在ngclass-mix-expressions可参与更多讨论。
三、ExpressionChangedAfterItHasBeenCheckedError
我试图在ngAfterViewInit()中改变变量时会抛出错误,这时需要把代码写到setTimeout()内延迟执行才不会报错。
具体原因查看Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)。