一、Angular介绍
https://angular.cn/docs
Angular是谷歌开发的一款开源的 web 前端框架,诞生于2009年,由 Misko Hevery等
人创建,后为 Google 所收购。是一款优秀的前端JS框架。
Angular 基于 TypeScript 和 react、vue相比,Angular 更适合中大型企业级项目。
二、学习Angular 必备基础
必备基础:html、css、js、es6、Typescript、rxjs
三、Angular 环境搭建
1、安装前准备工作
安装nodejs稳定版本
2、安装angular/cli脚手架
npm install -g @angular/cil
//安装指定版本
npm install -g @angular/cli@7.3.9
3、检查版本号
ng --version 或者ng v
四、Angular 项目创建
1、打开命令行工具找到你要创建项目的目录
2、创建项目
ng new 项目名称
//如果要跳过npm i 安装
ng new 项目名称--skip-install后用cnpm install
3、根模块说明
declarations:[] //配置当前项目运行的组件
imports:[] //配置当前模块运行依赖的其他模块
providers:[] //配置项目所需要的服务
bootstrap:[] //指定应用的主视图(根组件)通过引导根appModule 来启动应用
4、通过cli 创建组件、服务、类等
ng g 可以查看可以创建的类型
//创建组件
ng g c components/news <==> ng generate component components/news
//创建服务
ng g service services/storage
五、开发中常用知识点
1、组件
@Component装饰器会指出紧随其后的那个类是个组件类。
@Component({
selector: 'app-hero-list',
templateUrl:'./hero-list.component.html',
providers:[HeroService]
})
export class HeroListComponent implements OnInit{
/*...*/
}
2、依赖注入
在Angular 中,要把一个类定义为服务,就要用@Injectable()装饰器来提供元数据,
以便让 Angular 可以把它作为依赖注入到组件中。@Injectable()装饰器来表明一个组
件或其它类(比如另一个服务、管道或NgModule)拥有一个依赖。
<div>{{username}}</div>
//静态数据
<div title="我是一个div"></div>
//动态数据
<div [title]="username"></div>
//解析HTML
<div [innerHTML]="content"></div> content='<h2>我是一个div</h2>'
//运算
<div>{{1+2}}</div>
3、*ngFor 循环
items:any[] = [111,222,33,444];
items:Array<any> = ['1111',2222];
<ul>
<li *ngFor="let item of items;let i = index">{{index}}----{{item}}</li>
</ul>
4、*nglf条件判断
flag:boolean=false;
<div *ngIf="flag">这是一个ngIf判断是否显示</div>
<div *ngIf="!flag">这是一个ngIf判断是否显示</div>
5、*ngSwitch
<ul [ngSwitch]="type">
<li *ngSwitchCase="1">微信</li>
<li *ngSwitchCase="2">支付宝</li>
<li *ngSwitchCase="3">银联</li>
<1i *ngSwitchDefault>无效</li>
</ul>
7、属性[ngClass]、[ngStyle]
ts: flag:boolean=true;
activeColor:string='red';
css: active{color:red};
//动态绑定class
<div [ngClass]="{'active':flag}"></div>
<div [ngClass]-"{'active':!flag}"></div>
<div [ngClass]="{'orange':flag,'red':!flag}"</div>
<p [ngStyle]="{'color':'red'}">我是一个P标签</p>
<p [ngStyle]="{'color':activeColor}">我是一个P标签</p>
8、管道(pipe)
用来对输入的数据进行处理、如大小写转换、数值和日期格式化
<p>{{str | uppercase}}</p>//转换成大写
<p>{{str | lowercase}}</p>//转换成小写
<p>{{today | date:'yyyy-MM-dd HH:mm:ss'}}</p>
//小数位数 接收参数格式为{最少整数}.{最少小数位数}-{最多小数位数}
<p>{{num | number:'1.2-4'}}</p>//保留2~4位小数
9、执行事件
<button (click)="submit()"></button>//点击事件
<input type="text" (blur)="blurHander()"/>//blur事件
<input type="text" (keydown)="keyDownHander($event)"/>//键盘事件
六、双向数据绑定
注意引入:FormsModule
//app.module.ts
Import { FormsModule } from '@angular/forms';
imports: [ FormsModule ]
<input type="text" [(ngModel)]="inputValue">
<p>{{inputValue}}</p>
七、ViewChild
1、操作dom
<div #myattr>我是一个dom节点</div>
import { Component, ViewChild, ElementRef } from '@angular/core'
@ViewChild('myattr') myattr:ElementRef;
ngAfterViewInit(){
this.myattr.nativeElement.style.width='100px';
}
2、父子组件中通过ViewChild 调用子组件的方法
<app-child #child></app-child>
//获取子组件的实例
@ViewChild('child') mychild : ElementRef;
//直接调用子组件内部的方法
this.mychild.run();
八、父子组件之间通讯
1、父组件给子组件传值 @Input 装饰器
//父组件传值
<app-header [msg]="msg"></app-header>
//子组件引入Input模块
Import { Input } from '@angular/core'
//子组件使用@Input 接收父组件传过来的数据
@Input() msg : string;
2、子组件通过 @Output触发父组件的方法
//子组件引入Output和EventEmitter
Import { Output, EventEmitter } from '@angular/core'
//子组件中实例化 EventEmitter
@Output() private outer = new EventEmitter<string>();
//子组件中广播
this.outer.emit('msg form child');
//父组件调用子组件的时候,定义接收事件,outer 就是子组件的EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header>
九、生命周期函数
生命周期函数通俗的讲就是组件创建、组件更新、组件销毁的时候会触发的一系列的方
法。
1、当Angular 使用构造函数新建一个组件或指令后,就会按下面的顺序在特定时刻调
用这些生命周期钩子方法
2、只执行一次的钩子
ngOnInit
ngAfterContentInit
ngAfterViewInit
ngOnDestroy
3、多次执行的钩子
ngOnChanges
ngDoCheck
ngAfterContentChecked
ngAfterViewChecked
十、路由
路由就是根据不同的 url 地址,动态让根组件挂载其他组件来实现一个单页面应用
1、配置路由
//路由模块 app-routing.module.ts
import { Routes, RouterModule } from '@angular/router';
const routes : Routes = [
{path:'home',component:HomeComponent},
{path:'news',component:NewsComponent},
{path:"',redirectTo:'/home',pathMatch:'full'},
{path:'**',redirectTo:'/home'}//匹配不到路由的时候加载的组件
];
routerLink 跳转页面默认选中路由
/*routerLinkActive 选中状态/
<h1>
<a routerLink="/home" routerLinkActive="active">首页</a>
<a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>
<router-outlet></router-outlet>
3、根模块加载路由
import { AppRoutingModule } from './app-routing.module';
//动态加载路由的地方
imports:[AppRoutingModule]
4.参数传值
<a [routerLink]="['/newsDetail']" [queryParams]="{id:123}">详情</a>
//接收
import { ActivatedRoute } from '@angular/router';
constructor(public route : ActivatedRoute){ }
this.route.queryParams.subscribe((data)=>{
console.log(data);
})
5、动态路由传值
{path:'newsDetail/:id',component:NewsDetailComponent}
<a [routerLink]="['/newsDetail',key]">详情</a>
//获取值
import { ActivatedRoute } from '@angular/router';
constructor(public route : ActivatedRoute){ }
this.route.params.subscribe((data)=>{
console.log(data);
})
6、js 路由跳转
import { Router } from '@angular/router';
constructor(public route : Router){}
goNewsDetail(){
this.route.navigate(['/newsDetail','1234'])
}
import{ Router, NavigationExtras } from '@angular/router';
goNewsDetail(){
let navigationExtras : NavigationExtras ={
queryParams:{'id':'123'}
}
this.router.navigate(['/news'],navigationExtras);
}
7、嵌套路由
{
path : 'home', component : HomeComponent,
children : [
{ path : 'welcome', component : WelcomeComponent }
{ path : 'setting', component : SettingComponent }
]
}
//home页面
<router-outlet></router-outlet>
十一、Rxjs 异步数据流编程
1、RxJs 处理异步
import { Observable } from 'rxjs';
//创建可观察对象
let stream= new Observable(observer=>{
setTimeout(()=>{
observer.next('observable timeout');
},2000);
});
//订阅
stream.subscribe(value=>console.log(value));
Rxjs相比Promise要强大很多。比如Rxjs 中可以中途撤回、可以发射多个值、提供了
多种工具函数等等。
2、取消订阅unsbscribe()
//订阅
const d= stream.subscribe(value=>console.log(value));
setTimeout(()=>{
d.unsubscribe();
},1000)
3、订阅后多次执行
//pormise 方式
getPromiseIntervalData(){
return new Promise((resolve)=>{
setInterval(()=>{
resolve('promise 只会执行一次”);
},1000)
})
}
//rxjs方式
getRxjsIntervalData(){
return new Observable((observer)=>{
setInterval(()=>{
observer.next('rxjs 多次执行一次');
},1000)
})
}
4、工具函数
//map,filter
import { map,filter } from 'rxjs/operators';
stream.pipe(
filter(val=>val%2 == 0),
map(value=>{
return value*value
})
)
//延迟执行
.import { Observable, fromEvent } from 'rxjs';
.import { map, filter, throttleTime } from 'rxjs/operators';
.const button = document.querySelector('button');
.fromEvent(button,'click').pipe(
. throttleTime(1000)
.).subscribe(()=>console.log('clicked'))
十二、Angular 中的数据交互
get 请求
//app.module.ts中引入HttpClientModule 并注入
import { HttpClientModule } from '@angular/common/http';
imports : [HttpClientModule]
//在用到的地方引入HttpClient 并在构造函数声明
import { HttpClient, HttpHeaders } from '@angular/common/http';
//依赖注入
constructor(public http : HttpClient){}
//get 请求
const api='http://xxxxxxxx'
this.http.get(api).subscribe(response=>{
console.log(response)
})
post 请求
//手动设置请求类型
const httpOptions = {
headers : new HttpHeaders({'Content-Type':'application/json'})
}
this.http.post(api, {username:'admin',password:'123456'}, httpOptions).subscribe(response=>{
console.log(response)
})
网友评论