angular2學習筆記之ng2標籤

angular2的內值指令和angular2很相似,全部熟悉angular1的朋友看一眼就會了。angular2-demo
<!-- more -->
點擊訪問小莫的githubcss

1、 效果圖

1、指令解讀

0. 組件

主要就是定義了一些數據用於測試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'
        };
    };
}

1. ngFor

<ul class="list-group" *ngFor="let item of list">
  <li class="list-group-item">{{item.name}}</li>
</ul>

效果圖
git

2. ngIf

我在組件中定義了一個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

3. ngSwitch

我在組件中定義了一個方法,能夠設置選中的值給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

4. ngStyle

這裏的樣式的值都是從組件中取出來的,也就意味着它能夠動態,不過建議是封裝成class,也就是ngClassthis

<div [ngStyle]="{'background-color': ngStyleList.backgroundColor,'color':ngStyleList.color}" [style.font-size]="30">
      背景 :{{ngStyleList.backgroundColor}} <br/>
      字體顏色: {{ngStyleList.color}}
  </div>

效果圖

5. ngClass

左邊是class名[要用''包起來],右邊是一個true|false表達式

<button class="btn" [ngClass]="{'btn-danger': ngStyleList}">測試</button>

效果圖

相關文章
相關標籤/搜索