angular2的思想很是先進,摒棄了angular1那種複雜的構建模式,採用了組件化開方的方,那咱們一塊兒來看一看,一個基礎的組件是什麼樣子的呢。angular2-democss
.ts
組件代碼html
.scss
樣式git
.png
效果圖github
.html
模板文件angular2
https://github.com/qq83387856/angular2-demo/tree/master/src/ts/component/basic函數
一個基本的組件就長個樣子,並無那麼神祕組件化
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]; }; }
這裏使用了uuid來建立一個隨機的id做爲惟一標識符
使用 public
能夠不用再 this.name = name
ui
import { uuid } from './../util/uuid'; export class UserModel{ id :string; constructor(public name:string){ this.id = uuid(); } }
使用ngFor 循環,index能夠取到索引值(從0開始)this
<div> <ul *ngFor="let item of users; let i = index"> <li>{{i+1}} Hello {{item.name}}</li> </ul> </div>