Angular4 - 启动过程
1.学习条件
本人由于项目组的变换,然后导致需要学习使用Angular 4,对于一个以前没有在项目开发中使用Angular的人来说,感觉到很无助,为什么呢?因为现在使用的Angular 4,前面还有AngularJS和Angular 2,岂不是说我需要去把这些东西都看完。
随着在网上找到一些资料,了解到首先AngularJS与Angular2.0属于不同的架构,然后Angular 4是对于Angular 2.0的升级,所以我们不用有心理负担去学习Angular 4.
由于本人没有学习过AngularJS,所以这里不介绍了。还是看一下Angular 4的架构图吧,至于内部的东西我们在下面的内容会介绍。
学习angular4的基本条件:
前端基础知识:html,css,js
不需要AbgularJS的知识
最好了解TypeScript语法
2. 安装软件以及创建新项目
nodejs
npm install-g @angular/cli
Webstorem
创建新项目
ng new projectName
3. 项目启动过程以及术语介绍
先看一张图,然后我们随着图的顺序来学习:
(1)Angular-cli的配置文件(①线)
"index": "index.html"
启动时加载了哪些脚本
"main": "main.ts".
(2)引入必备的包,然后启动AppModule
platformBrowserDynamic().bootstrapModule(AppModule)/*启动程序*/
.catch(err => console.log(err));
(3)启动Appmodule(由③到④)
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
exports: [ AppComponent ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
imports 本模块声明的组件模板需要的类所在的其它模块。
providers 服务的创建者,并加入到全局服务列表中,可用于应用任何部分。
declarations 声明本模块中拥有的视图类。Angular 有三种视图类:组件、指令和管道。
exports declarations 的子集,可用于其它模块的组件模板。
bootstrap 指定应用的主视图(称为根组件),它是所有其它视图的宿主。只有根模块才能设置 bootstrap 属性。
bootstrap: [AppComponent]
(4)AppComponent
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
组件是一个装饰器,他能接受一个配置对象, Angular 会基于这些信息创建和展示组件及其视图。组件元素据装饰器是用来告知angualr如何将一个类处理成一个angular的组件,至于如何处理,就要看里面的配置了。
selector:CSS 选择器,它告诉 Angular 在父级 HTML 中查找 <app-root> 标签,创建并插入该组件。
templateUrl:当前组件的内容。在selector调用的地方放置模板的内容。如果使用 template 来写的话是用“`”这个符号来直接编写 HTML 代码。
styleUrls: 指向一组css文件,当前组件的css内容
(5)渲染界面
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Auction</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
在这里我么你发现了这个app-root标签,那我们也就找到了AppComponent组件template要插入的位置,然后Angular将./app.component.htm的内容替换到这里,然后引入css文件,也就是组件部分定义的./app.component.css。这样就是页面上的渲染就已经OK了,然后对于当前页面上的事件绑定,数据展示,逻辑处理,那都是之前介绍的组件控制器来进行交互了。
(6)验证页面
<!---app.component.html-->
<span>
App Component show succesfully!
</span>
/*app.component.css*/
span {
color: red;
}
页面的渲染情况就不贴图了,因为没有什么内容,比较空洞,贴出来不太好看。