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>
相关文章
相关标签/搜索