angular2系列教程(三)components
来源:互联网 发布:网络玄幻小说合集下载 编辑:程序博客网 时间:2024/06/05 06:00
今天,我们要讲的是angualr2的components。
例子
这个例子是个老外写的,我将其迁移到angular2beta版本,想了解迁移的同学可以参考我的做法。
源代码
消失的控制器
angular2的组件就是angual1中的指令。它包含模板、样式、注入、和选择器。
组件嵌套组件可以实现类似react的模块化,我曾经也用angular1做过类似的事情
Angular 结合RequireJs实现模块化开发
我当时就想,既然有了指令(ng1)还要什么控制器(ng1)啊!果不其然ng2中移除了控制器,直接用指令也就是ng2的组件来展示界面:
app/navbar.ts
import { Component} from 'angular2/core';import {NgFor} from 'angular2/common'@Component({ selector: "navbar", directives: [NgFor], styles: [` li{ color: gray; } `], template: ` <h2>Democratic Party presidential candidates</h2> <ul> <li *ngFor="#item of items; #i = index">{{item}} {{i}}</li> </ul> `})export class Navbar { items: Array<String> constructor() { this.items = [ "Hillary Clinton", "Martin O'Malley", "Bernie Sanders" ] } ngOnInit() { console.log('[Component] navbar onInit'); }}
当组件被实例化后,ng2为这个组件创建了一个shadow DOM(Shadow DOM在一个web组件中提供了js,css,template的封装),然后模板和样式被注入进去。
这段代码做了这些事情:
- 设置选择器
- 设置directives为[ngFor]
- 设置样式
- 设置模板
- 填写类的成员变量items
- 在构造函数中给items添加数据
- 在生命周期的钩子ngOnInit中打印信息
我们的组件就写好了。
组件的嵌套
写好组件后,我们如何将这个组件放在app组件中呢?答案是directives。这里设计得没有react好,react的组件是可以直接用的,angular2的组件则需要以指令的身份注入,因为组件实质也是指令:
app/app.ts
import {Component} from 'angular2/core';import {bootstrap} from 'angular2/platform/browser';import {Navbar} from './navbar';@Component({ selector: "app", directives:[Navbar], template: ` <navbar></navbar> `})export class App { constructor() { }}bootstrap(App, []) .catch(err => console.error(err));
ng2中组件和指令都是注入在directives中,directives包含三种类型:
- Components
- Structural directives
- Attribute directives
关于指令,我们会单独拿出来讲解。
生命周期钩子
本例中,我们使用了ngOnInit这个类方法去打印一个信息,这个方法会在组件初始化时候调用。组件存在很多声明周期钩子函数
ngOnChanges
ngOnInit
ngOnDestroy
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
Official docs
0 0
- angular2系列教程(三)components
- Angular2教程(三)
- angular2系列教程(四)Attribute directives
- angular2系列教程(二)模板语法
- angular2系列教程(一)hello world
- ASP.NET 5系列教程 (三):view components介绍
- ASP.NET 5系列教程 (三):view components介绍
- Angular2入门系列教程-服务
- angular2系列教程(七)Injectable、Promise、Interface、使用服务
- angular2系列教程(九)Jsonp、URLSearchParams、中断选择数据流
- Angular2教程(一)
- Angular2教程(二)
- Angular2教程(四)
- Angular2教程(五)
- Angular2教程(六)
- Angular2教程(七)
- 数据结构系列教程(三)
- MySQL系列教程(三)
- BZOJ1036--树链剖分模板
- NSProxy学习
- angular2系列教程(四)Attribute directives
- android 开发时报错Unsupported major.minor version 52.0
- 图像分割任务中的尺度问题
- angular2系列教程(三)components
- hdu 1142 A Walk Through the Forest 最短路+记忆化搜索
- 学习Maven 遇到的问题
- DFSORT 简单用例
- 二叉树的最小深度
- 加密解密相关网页
- hdu 1506 Largest Rectangle in a Histogram
- 字符串扩展
- angular2系列教程(二)模板语法