淺談Angularjs至Angular2後內置指令的變化

image.png

1、科普概要說明
  • 咱們常說的 Angular 1 是指 AngularJS; 從Angular 2 開始已經更名了。再也不帶有JS,只是單純的 Angular
  • Angular 1.x 是基於JavaScript的框架,Angular2後是基於 TypeScript來寫的
    有興趣的朋友能夠了解下NG-ZORRO Ant Design of Angular https://ng.ant.design/docs/introduce/zh
  • Angular 官方文檔 地址https://angular.io/
  • 開發腳手架 https://cli.angular.io/
  • TypeScript 入門文檔 https://www.typescriptlang.org/
    初步瞭解下TypeScript的語法
    image.png
2、詳解部份內置指令的變化

(1)、Angular(ng-if) -- Angular2(*ngIf)typescript

語法 <element ng-if="expression"></element>
ng-if 指令用於在表達式爲 false 時移除 HTML 元素。
若是 if 語句執行的結果爲 true,會添加移除元素,並顯示

<div *ngIf="false"></div>
<div *ngIf="myFunction()"></div>

(2)、Angular(ng-repeat) -- Angular2(*ngFor)express

ng-repeat 指令用於循環輸出指定次數的 HTML 元素。集合必須是數組或對象
Angular 2.x 中不存在 ng-repeat 指令,取而代之的是 ngFor 指令。它們的語法很是類似,
但須要注意的一點在遍歷集合是,Angular 2 使用 of 代替了 in 。
<tr ng-repeat="x in records">
        <td>{{x.Name}}</td>
        <td>{{x.Country}}</td> 
</tr>
<ul>
        <li *ngFor="let grocery of groceries; let i = index;">
          <a href="#" (click)="selectGrocery(grocery);">
            {{ grocery.label }} {{ i }}
          </a>
        </li>
</ul>

(3)、Angular(ng-switch) -- Angular2(ngSwitch)數組

ng-switch 指令根據表達式顯示或隱藏對應的部分。
對應的子元素使用 ng-switch-when 指令,若是匹配選中選擇顯示,其餘爲匹配的則移除。
你能夠經過使用 ng-switch-default 指令設置默認選項,若是都沒有匹配的狀況,默認選項會顯示。
做用 防止條件複雜的狀況致使過多的使用 ngIf。
<element ng-switch="expression">
  <element ng-switch-when="value"></element>
  <element ng-switch-when="value"></element>
  <element ng-switch-when="value"></element>
  <element ng-switch-default></element>
</element>

<div class="container" [ngSwitch]="myAge">
 <div *ngSwitchCase="'10'">age = 10</div>
 <div *ngSwitchCase="'20'">age = 20</div>
 <div *ngSwitchDefault="'18'">age = 18</div>
</div>

(4)、Angular(ng-style) -- Angular2(ngStyle)框架

ng-style 指令爲 HTML 元素添加 style 屬性。
ng-style 屬性值必須是對象,表達式返回的也是對象。對象由 CSS 屬性和值組成,即 key=>value 對。
使用動態值給特定的 DOM 元素設定 CSS 屬性。
<h1 ng-style="{
        "color" : "white",
        "background-color" : "coral",
        "font-size" : "60px",
        "padding" : "50px"
    }">菜鳥教程</h1>

<div [style.color]="yellow">
</div>
<div [style.background-color]="backColor">
</div>
<div [style.font-size.px]="20">
</div>
<div [ngStyle]="{color: 'white', 'background-color': 'blue', 'font-size.px': '20'}">
</div>

(5)、Angular(ng-class) -- Angular2(ngClass)this

ng-class 指令用於給 HTML 元素動態綁定一個或多個 CSS 類。
ng-class 指令的值能夠是字符串,對象,或一個數組。
若是是字符串,多個類名使用空格分隔。
若是是對象,須要使用 key-value 對,key 爲你想要添加的類名,value 是一個布爾值。只有在 value 爲 true 時類纔會被添加。
若是是數組,能夠由字符串或對象組合組成,數組的元素能夠是字符串或對象。
<div ng-class="home">
    <h1>Welcome Home!</h1>
    <p>I like it!</p>
</div>
<div [ngClass]="{active: isActive}">               // 例子1
<div [ngClass]="{active: isActive,
                 shazam: isImportant}">            // 例子2
<div [class.active]="isActive">               // 例子3

在第一個例子中,若是isActive爲真,則active類被應用到那個元素上。
還能夠同時指定多個類,例如第二個例子。
Angular還有類綁定,它是單獨添加或移除一個類的好辦法,就像第三個例子中展現的。

(6)、Angular(ng-click) -- Angular2((click))雙向綁定

HTML 元素被點擊後須要執行的操做
<element ng-click="expression"></element>
<button (click)="toggleImage()">        // 例子1
<button (click)="toggleImage($event)">    // 例子2
在第一個例子中,當用戶點擊此按鈕時,相關組件中的toggleImage()方法就被執行了。
第二個例子演示瞭如何傳入$event對象,它爲組件提供了此事件的詳情。

(7)、Angular(ng-model) -- Angular2(ngModel)code

<element ng-model="name"></element> 綁定了 HTML 表單元素到 變量中
單向綁定 - [ngModel]
<form novalidate #f="ngForm">
      Name: <input type="text" name="username" [ngModel]="user.username">
   </form>
雙向綁定 - [(ngModel)]
<form novalidate #f="ngForm">
      Name: <input type="text" name="username"  [(ngModel)]="user.username">
   </form>

(8)、Angular(ng-value) -- Angular2(ngModel)orm

ng-value 指令用於設置 input 或 select 元素的 value 屬性。
<input ng-value="myVar">
 <select id='personHobbies' class='form-control'
          name='personHobbies' [(ngModel)]='activePerson.hobbyList[i]'>
          <option *ngFor='let h of hobbyListSelect;' [ngValue]='h'>{{h.name}}</option>
        </select>

最後科普下Angular 父子組件之間參數傳遞的問題 (@input @output :在子組件引入父組件的元素時,@Input每每是值,@Output是指事件)對象

父組件到子組件:父組件用屬性綁定將值傳入,子組件經過@Input來接收。
// 父組件
import { Component } from '@angular/core'; 
@Component({
  selector: 'hero-parent',
  template: `<h2> heroes </h2>
    <hero-child *ngFor="let hero of heroes"
      [hero]="hero" >
    </hero-child>
  `
})
export class HeroParentComponent {
  heroes = [{
    name: 'John'
  }, {
    name: 'Lily'
  }]; 
}
// 子組件
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
  selector: 'hero-child',
  template: `
    <h3>{{hero.name}}</h3> 
  `
})
export class HeroChildComponent {
  @Input() hero: Hero; 
}

子組件到父組件:子組件自定義事件用@Output傳出,父組件用事件綁定獲取。
// 子組件
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
  selector: 'my-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)">Agree</button> 
  `
})
export class VoterComponent { 
  @Output() onVoted = new EventEmitter<boolean>(); 
  vote(agreed: boolean) {
    this.onVoted.emit(agreed); 
  }
}
// 父組件
import { Component } from '@angular/core';
@Component({
  selector: 'vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
    <my-voter *ngFor="let voter of voters"
      [name]="voter"
      (onVoted)="onVoted($event)">
    </my-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}
父組件的類須要讀取子組件的屬性值或調用子組件的方法:子組件做爲ViewChild,注入到父組件裏面

image.png

image.png

相關文章
相關標籤/搜索