Angular中ng开头的属性及元素整理ing

1. *ngIf 

结构型指令,用于条件判断,控制dom元素在html文件中的显示,使用时前面要加*。

<div *ngIf="data"></div>

2. *ngFor of

结构型指令,用于循环遍历生成html文档,对于数据可方便的通过ngFor遍历出具有相同dom结构的html元素,使用时前面要加*。

data=[{name:"aaa",value:0},{name:"bbb",value:1},{name:"ccc",value:0}]
<ul>
  <li *ngFor="let item of data">{{item.name}}</li>
</ul>

3. ngSwitch

结构性指令,根据表达式的值渲染添加显示的DOM元素

<div [ngSwitch]="switch_expression">
  <!-- the same view can be shown in more than one case -->
  <div *ngSwitchCase="match_expression_1">...</div>
  <div *ngSwitchCase="match_expression_2">...</div>
  <div *ngSwitchCase="match_expression_3">...</div>
  <!--default case when there are no matches -->
  <div *ngSwitchDefault>...</div>
</div>

4. ngStyle

属性指令,用于更新容器元素的样式。

<div [ngStyle]="{'color': 'red'}">...</div>

或者使用更复杂的方式

<div [ngStyle]="formatStyle(item)">...</div>
formatStyle(item){
  let value = item.value;
  let color = "white";
  if(value===0){
    color = "red";
  }
  return {
    "backgroundColor":color}
  }
}

5. ngClass

属性选择器,从 HTML 元素上添加和移除 CSS 类。

<div [ngClass]="{'first': true, 'second': true, 'third': false}">...</div>

6. ng-container

 <ng-container> 是一个分组元素,但它不会污染样式或元素布局,因为 Angular 压根不会把它放进 DOM 中

<p>
  I turned the corner
  <ng-container *ngIf="hero">
    and saw {{hero.name}}. I waved
  </ng-container>
  and continued on my way.
</p>

7. ng-template

<ng-template>是一个 Angular 元素,用来渲染 HTML。 它永远不会直接显示出来。 事实上,在渲染视图之前,Angular 会把 <ng-template> 及其内容替换为一个注释。

<p>Hip!</p>
<ng-template>
  <p>Hip!</p>
</ng-template>
<p>Hooray!</p>

中间的Hip!就不会出现

8. ng-content

Angular中需要创建模板,以在多个组件中复用同一模板时,在模板组件中使用<ng-content></ng-content>来添加不同的DOM元素或组件。

<div class="red-dot">
    <ng-content></ng-content>
</div>

  同一html文件中有多个<ng-content>时,使用select进行选择

<div class="red-dot">
    <ng-content select="[name=layoutCenter]"></ng-content>
</div>
<div class="blue-border">
    <ng-content select="[name=layoutBottom]"></ng-content>
</div>

  

<div class="content">
    <app-my-component name="layoutCenter"></app-my-component>
</div>

9.ngModel

双向数据绑定

<input type="text" [(ngModel)]="value"/>

注意组件所在module需引入FormsModule

import {FormsModule} from '@angular/forms';

10.ngForm

Angular表单

<form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)">
  <label for="name">Name <input class="form-control" name="name" ngModel required />
  </label>
  <button type="submit">Submit</button>
</form>

 

posted @ 2021-01-15 16:02  Viola_left  阅读(353)  评论(0编辑  收藏  举报