• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
邹天得
博客园    首页    新随笔    联系   管理    订阅  订阅

angular2学习笔记之基本组件和ngFor

http://www.tuicool.com/articles/eMnQfmQ

时间 2016-06-30 16:55:35  好JSER
原文  http://hao.jser.com/archive/10992/
主题 AngularJS

angular2的思想非常先进,摒弃了angular1那种复杂的构建模式,采用了组件化开方的方,那我们一起来看一看,一个基础的组件是什么样子的呢。 angular2-demo

一、简介

1. 目录结构

  • .ts 组件代码

  • .scss 样式

  • .png 效果图

  • .html 模板文件

2. 效果图

二、代码实例

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

三、 详细解读

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 = name

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

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

3. Basic.html

使用ngFor 循环,index可以取到索引值(从0开始)

<div>
    <ul *ngFor="let item of users; let i = index">
        <li>{{i+1}} Hello {{item.name}}</li>
    </ul>
</div>
posted on 2017-05-03 23:26  邹天得  阅读(547)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3