angular [NgClass] [NgStyle],NgIf,[ngSwitch][ngSwitchCase]

[NgClass]

CSS 类会根据表达式求值结果进行更新,更新逻辑取决于结果的类型:

  • string - 会把列在字符串中的 CSS 类(空格分隔)添加进来,

  • Array - 会把数组中的各个元素作为 CSS 类添加进来,

  • Object - 每个 key 都是要处理的 CSS 类,当表达式求值为真的时候则添加,为假则移除。

<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

//  如果 isShow=true,添加  first, second 这两个类, 移除 third 这个类
<some-element [ngClass]="{'first': isShow, 'second': isShow, 'third': !isShow}">...</some-element>
// <some-element [ngClass]="{isShow ? 'first':'second'}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> // 如果 isShow=true,添加 class1, class2 , class3 <some-element [ngClass]="{'class1 class2 class3' : isShow}">...</some-element>

[NgStyle]

[ngStyle] 可以通过指定用冒号分隔的键值对来设置一个或多个样式属性
<some-element [ngStyle]="objExp">...</some-element>
<some-element [ngStyle]="{cursor: 'pointer'}">...</some-element>

<some-element [ngStyle]="{marginBottom:'30px',background:'#F1F1F1',border:'1px #d9d9d9 solid'}">...</some-element>

// 动态添加样式 
<some-element [ngStyle]="{backgroundColor:(item.leftColor)}">...</some-element>

// 动态添加样式 
<some-element [ngStyle]="{'left': (400 - node.level * 18) + 'px'}">...</some-element>

通常使用指令的简写形式*ngIf=“condition”,作为插入模板的锚元素的属性提供。Angular将其扩展为更明确的版本,其中锚元素包含在<ng template>元素中。

// 如果condition 为true 则渲染

<div *ngIf="condition">Content to render when condition is true.</div>

<ng-template [ngIf]="condition"><div>Content to render when condition is
true.</div></ng-template>

// 如果condition 为true 则渲染div, 否则渲染 elseBlock

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

//  // 如果condition 为true 则渲染thenBlock , 否则渲染 elseBlock
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

[ngSwitch][ngSwitchCase]

当下一个匹配表达式与开关表达式匹配时添加或删除模板(显示或隐藏视图)的结构指令。

容器上的[ngSwitch]指令指定要与之匹配的表达式。要匹配的表达式由容器中视图的ngSwitchCase指令提供。

匹配的每个视图都会被渲染。

如果没有匹配项,则呈现具有ngSwitchDefault指令的视图。

在[NgSwitch]语句中,但在任何NgSwitchCase或ngSwitchDefault指令之外的元素都保留在该位置。

<container-element [ngSwitch]="switch_expression">
    // 匹配时,显示相应的视窗
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  // 没有匹配项时的默认情况
  <some-element *ngSwitchDefault>...</some-element>
</container-element>