angular2的內值指令和angular2很相似,全部熟悉angular1的朋友看一眼就會了。angular2-demo
<!-- more -->css
主要就是定義了一些數據用於測試html
import {Component} from '@angular/core'; @Component({ selector: 'ng-tag', styles: [require('./NgTag.scss')], template: require('NgTag.html') }) export class NgTagComponent { list:any; ngSwitchList:any; ngStyleList:any; constructor() { this.list = [{ 'name': 'xiaomo' },{ 'name': 'xiaogang' },{ 'name': 'xiaomoxue' }]; this.ngSwitchList=[ 'xiaomo', 'xiaoming' ]; this.ngStyleList={ 'color':'blue', 'backgroundColor':'green' }; }; }
<ul class="list-group" *ngFor="let item of list"> <li class="list-group-item">{{item.name}}</li> </ul>
效果圖git
我在組件中定義了一個listgithub
this.list = [{ 'name': 'xiaomo' },{ 'name': 'xiaogang' },{ 'name': 'xiaomoxue' }];
我在循環這個數組對象的時候去比對item.name 若是是 xiaomo
,就 出現 ngIf中的內容數組
<ul *ngFor="let item of list"> <li *ngIf="item.name=='xiaomo'" class="list-group-item">哇,我在list列表中找到了 <span class="label label-info">{{item.name}}</span></li> </ul>
效果圖angular2
我在組件中定義了一個方法,能夠設置選中的值給myVal測試
myVal:number = 0; changeValue($event):void{ console.log($event.target.value);// 輸出選中的值設給myVal this.myVal = $event.target.value; }
有一組單選按鈕,選中是myVal
會改變,ngSwitch
會去循環每一個case
,若是找到了就顯示那條case
中的數據,否則顯示default
中的數據字體
<div> <h2>ngSwitch</h2> <input name="myVal" type="radio" title="" value="1" (click)="changeValue($event)">1 <input name="myVal" type="radio" title="" value="2" (click)="changeValue($event)">2 <input name="myVal" type="radio" title="" value="3" (click)="changeValue($event)">3 <input name="myVal" type="radio" title="" value="4" (click)="changeValue($event)">4 <input name="myVal" type="radio" title="" value="5" (click)="changeValue($event)">5 <hr> <span [ngSwitch]="myVal"> <span *ngSwitchCase="'1'">ONE</span> <span *ngSwitchCase="'2'">TWO</span> <span *ngSwitchCase="'3'">THREE</span> <span *ngSwitchCase="'4'">FOUR</span> <span *ngSwitchCase="'5'">FIVE</span> <span *ngSwitchDefault>other</span> </span> </div>
效果圖ui
這裏的樣式的值都是從組件中取出來的,也就意味着它能夠動態,不過建議是封裝成class,也就是ngClass
this
<div [ngStyle]="{'background-color': ngStyleList.backgroundColor,'color':ngStyleList.color}" [style.font-size]="30"> 背景 :{{ngStyleList.backgroundColor}} <br/> 字體顏色: {{ngStyleList.color}} </div>
效果圖
左邊是class名[要用''
包起來],右邊是一個true|false表達式
<button class="btn" [ngClass]="{'btn-danger': ngStyleList}">測試</button>
效果圖