angular2的思想非常先进,摒弃了angular1那种复杂的构建模式,采用了组件化开方的方,那我们一起来看一看,一个基础的组件是什么样子的呢。
一、简介
1. 目录结构
.ts
组件代码.scss
样式.png
效果图.html
模板文件
2. 效果图
二、代码实例
三、 详细解读
1.
一个基本的组件就长个样子,并没有那么神秘
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.
这里使用了uuid来创建一个随机的id作为唯一标识符
使用public
可以不用再 this.name = name
import { uuid } from './../util/uuid';export class UserModel{ id :string; constructor(public name:string){ this.id = uuid(); }}
3.
使用ngFor 循环,index可以取到索引值(从0开始)
- { {i+1}} Hello { {item.name}}