Angular CLI ng常用指令整理


一、組件創建

ng generate component heroes

二、運行項目

ng serve --open //--open 立即打開

三、創建指令

ng g directive my-new-directive 

四、創建管道

ng g pipe my-new-pipe

五、ngModel指令

1、雖然 ngModel 是一個有效的 Angular 指令,不過它在默認情況下是不可用的。

它屬於一個可選模塊 FormsModule,必須自行添加此模塊才能使用該指令。

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';

@NgModule({
  declarations: [
    AppComponent,
    HeroesComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 2、用法

<div>
    <label>name:</label>
    <input type="text" placeholder="name" [(ngModel)]="hero.name"/>
  </div>

六、ngFor指令

*ngFor 是一個 Angular 的復寫器(repeater)指令。 它會為列表中的每項數據復寫它的宿主元素。

不要忘了 ngFor 前面的星號(*),它是該語法中的關鍵部分。

 用法:

<ul>
    <li *ngFor="let hero of heroes">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
    </li>
</ul>

七、click事件綁定

語法:

<li *ngFor="let hero of heroes" (click)="onSelect(hero)">

八、ngIf指令

語法:

 <div *ngIf="selectedHero">
      <h2>{{selectedHero.name | uppercase}} Details</h2>
 </div>

九、ngStyle的基本用法

<p [ngStyle]="{'color': 'green'}">hello world!</p>
<p [ngStyle]="{'color':num == 2 ? 'red' : 'green'}">今天天氣真好!!!</p>

十、ngClass的基本用法

第一個參數為類名稱,第二個參數為boolean值,如果為true就添加第一個參數的類,基本用法:

<p [ngClass]="{'text-success': true}">被風吹過的夏天</p>
<p [ngClass]="{'text-success': username == 'zxc'}">西界</p>
<p [ngClass]="{'text-success': index  == 0}">黑鍵</p>

 栗子:

<ul>
    <li *ngFor="let item of arr, let i = index">
        <span [ngClass]="{'text-danger': i==0}">{{item}}</span> //循環顯示的第一行添加text-danger樣式,文字變紅色
    </li>
</ul>

十一、ngSwitch的基本用法

<div [ngSwitch]="num">
      <div *ngSwitchCase="1">顯示</div>
      <div *ngSwitchDefault>默認顯示</div>
</div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM