angular2學習筆記之基本組件和ngFor

angular2的思想很是先進,摒棄了angular1那種複雜的構建模式,採用了組件化開方的方,那咱們一塊兒來看一看,一個基礎的組件是什麼樣子的呢。angular2-demo
點擊訪問小莫的githubcss

1、簡介

1. 目錄結構

  • .ts 組件代碼html

  • .scss 樣式git

  • .png 效果圖github

  • .html 模板文件angular2

2. 效果圖

2、代碼實例

https://github.com/qq83387856/angular2-demo/tree/master/src/ts/component/basic函數

3、 詳細解讀

1. Basic.ts

一個基本的組件就長個樣子,並無那麼神祕組件化

import {Component} from '@angular/core';
import {UserModel} from './../../model/UserModel';

// 建立模擬數據
let xiaomo:UserModel = new UserModel( 'xiaomo');
let xiaoming:UserModel = new UserModel('xiaoming');

@Component({
    selector: 'basic',
    styles:[require('./Basic.scss')], //內聯樣式,注意使用row-loader
    template: require('./Basic.html')
})

export class BasicComponent {

    users:Object;
    // 在構造函數中賦值
    constructor() {
            this.users= [ xiaomo,xiaoming];
    };
}

2. UserModel.ts

這裏使用了uuid來建立一個隨機的id做爲惟一標識符
使用 public 能夠不用再 this.name = nameui

import { uuid } from './../util/uuid';

export class UserModel{
    id :string;
    constructor(public name:string){
            this.id = uuid();
    }
}

3. Basic.html

使用ngFor 循環,index能夠取到索引值(從0開始)this

<div>
    <ul *ngFor="let item of users; let i = index">
        <li>{{i+1}} Hello {{item.name}}</li>
    </ul>
</div>
相關文章
相關標籤/搜索