Angular学习总结-入门篇
?
目錄
一、?Angular介紹?
二、 學(xué)習(xí)Angular必備基礎(chǔ)?
三、 Angular環(huán)境搭建?
四、 Angular創(chuàng)建項目?
五、 Angular環(huán)境搭建以及創(chuàng)建項目的時候可能遇到的錯誤?
六、Angular開發(fā)工具介紹?
Angular項目結(jié)構(gòu)介紹?
創(chuàng)建組件/服務(wù)?
angular語法?
變量?
ngFor循環(huán)+ngIf判斷+ngSwitch?
動態(tài)修改樣式ngClass+ngStyle?
雙向數(shù)據(jù)綁定?
管道(Pipe)?
獲取dom節(jié)點(diǎn)?
ngOnInit獲取節(jié)點(diǎn)?
獲取dom節(jié)點(diǎn)?
父子組件通信?
父組件給子組件傳值?
子組件主動調(diào)用父組件方法?
父組件主動調(diào)用子組件的數(shù)據(jù)和方法?
組件生命周期?
異步編程?
Angular get請求?
Angular post請求?
Angular jsonp請求?
Augular axios請求數(shù)據(jù)?
路由?
路由配置?
Get路由傳值?
動態(tài)路由傳值?
JS跳轉(zhuǎn)-get路由傳值?
JS跳轉(zhuǎn)-動態(tài)路由傳值?
父子路由?
一、?Angular介紹
Angular是谷歌開發(fā)的一款開源的web前端框架,誕生于2009年,由Misko Hevery 等人創(chuàng)建,后為Google所收購。是一款優(yōu)秀的前端JS框架,已經(jīng)被用于Google的多款產(chǎn)品當(dāng)中。
根據(jù)項目數(shù)統(tǒng)計angular(1.x 、2.x 、4.x、5.x、6.x、7.x 、8.x、9.x)是現(xiàn)在網(wǎng)上使用量最大的框架。
Angular基于TypeScript和react、vue相比 Angular更適合中大型企業(yè)級項目。
目前2019年12月25日angular最新版本angular9.x。根據(jù)官方介紹,Angular每過幾個月就會更新一個版本。Angular2.x以后所有的Angular版本用法都是一樣的,此教程同樣適用于Angular7.x 、Angular8.x、Angular9.x 以及未來的其它版本....。
正在上傳…重新上傳取消null
學(xué)習(xí)Angular必備基礎(chǔ)
必備基礎(chǔ):html ?、css 、js、es6
如果有Typescript基礎(chǔ)更容易理解,沒有Typescript基礎(chǔ)也可以學(xué)此教程。此教程中用到的Typescript語法會詳細(xì)講解。
Typescript基礎(chǔ)入門教程:?TypeScript視頻教程免費(fèi)下載-6小時學(xué)會TypeScript入門實(shí)戰(zhàn)-IT營大地2020年更新_IT營
Angular環(huán)境搭建
1、安裝前準(zhǔn)備工作:
1.1、安裝nodejs
Node.js (nodejs.org)???訪問該網(wǎng)站下載穩(wěn)定版本的msi安裝包
修改安裝路徑
安裝結(jié)束后,通過node -v查看node版本
Npm -v查看npm版本 ??npm包管理器
npm install -g??下載全局包時會有個默認(rèn)存放路徑,默認(rèn)存放路徑查看指令: npm root -g
一般默認(rèn)路徑是:C:\Users\用戶名\AppData\Roaming\npm\node_modules
設(shè)置存放路徑:
npm config set?prefix?"F:\packages\node_global"
npm config set cache "F:\packages\node_cache"
Npm config list
做環(huán)境變量配置:
安裝angular的計算機(jī)上面必須安裝最新的nodejs--注意安裝nodejs穩(wěn)定版本
1.2、安裝cnpm
npm可能安裝失敗建議先用npm安裝一下cnpm用淘寶鏡像安裝
淘寶 NPM 鏡像
| npm install -g cnpm --registry=https://registry.npm.taobao.org |
Cnpm -v查看cnpm是否安裝成功
2、使用 npm/cnpm 命令安裝angular/cli ?(只需要安裝一次)
npm install -g @angular/cli????
Ng v驗(yàn)證安裝是否成功
Angular創(chuàng)建項目
ng?new 項目名稱 ??
不能使用cnpm安裝angular/cli ?
??
直接安裝:
ng new angulardemo ?--同時會安裝依賴包,執(zhí)行的命令就是npmi
如果要跳過npm i安裝:
ng new angulardemo --skip-install --不需要安裝依賴包
進(jìn)入到angulardemo 目錄下,執(zhí)行cnpm install 下載依賴包。如果不下載依賴包,執(zhí)行運(yùn)行程序會報錯
cd angulardemo
ng serve --open
Angular環(huán)境搭建以及創(chuàng)建項目的時候可能遇到的錯誤
解決方案:用 cnpm 安裝
解決方案1:ctrl+c結(jié)束項目,cd到項目里面,用 cnpm i 安裝依賴
解決方案2:創(chuàng)建項目的時候 ?--skip-install
| ng new my-app --skip-install cd my-app cnpm install ??/ ??yarn |
解決方案:用yarn 替代 cnpm和npm
1?cnpm instal @angular/cli (我的npm會報錯);
2?ng new 的時候阻止自動安裝ng包,只創(chuàng)建ng目錄? ? ?
| ng new my-app --skip-install |
?? ? ? ?
3 安裝yarn? ? ? ??npm install -g yarn? ?/? ? ? ?cnpm install -g?yarn? ?
4 進(jìn)入目錄my-app 使用yarn 安裝ng所依賴的包? ? ? ????yarn
注意:yarn 命令 等同于? npm install / cnpm install? ? ? ?使用yarn前提是先安裝yarn? ,安裝使用?cnpm install -g?yarn? ?就可以安裝
六、Angular開發(fā)工具介紹
1.Webstorm
2.Visual Studio Code
Visual Studio Code - Code Editing. Redefined
安裝插件
Angular項目結(jié)構(gòu)介紹
掛載方式:
創(chuàng)建組件/服務(wù)
創(chuàng)建組件: ng g component components/news
創(chuàng)建服務(wù): ng g service services/storage
服務(wù)沒法調(diào)用組件里的方法,組件之間也不能互相調(diào)用方法(除父子組件外)
創(chuàng)建服務(wù):
ng g service services/storage
在服務(wù)ts文件里創(chuàng)建方法
set(key:string,value:any) {
??localStorage.setItem(key,JSON.stringify(value));
}
get(key:string) {
??localStorage.getItem(key);
}
在app.module.ts引用
import {StorageService} from "./services/storage.service";
providers: [StorageService],
在具體組件中引用及調(diào)用服務(wù)接口
import {StorageService} from "../../services/storage.service";
constructor(public storageService:StorageService) { }
doSubmit() {
??this.storageService.set(this.people.name,this.people);
}
angular語法
變量
格式:[訪問權(quán)限] 變量名 [:數(shù)據(jù)類型] =’賦值’;
??????Public title:string=’我是一個標(biāo)題’;
訪問權(quán)限默認(rèn)是public,建議每個變量都加上對應(yīng)的數(shù)據(jù)類型
綁定屬性:
<img src="assets/images/02.png" alt="收藏" />
<img [src]="picUrl" />
動態(tài)屬性綁定記得用[]中括號
ngFor循環(huán)+ngIf判斷+ngSwitch
<ul>
??<li *ngFor="let item of arr;let key=index;">
????<span *ngIf="key % 2 == 0 "> {{item.name}} - {{item.age}} - {{key}}</span>
??</li>
</ul>
<ul [ngSwitch]="sex">
??<li *ngSwitchCase="1">男</li>
??<li *ngSwitchCase="2">女</li>
</ul>
<input type="radio" (click)="changeWoman()"> 女
<input type="radio" (click)="changeMan()" > 男
動態(tài)修改樣式ngClass+ngStyle
color:string='green';
flag:boolean = false;
.red {
??color: red;
}
.blue {
??color:blue;
}
.green {
??color:green;
}
<div class="red">
??靜態(tài)樣式
</div>
<br>
<div [ngClass]="{'red':flag,'blue':!flag}">
??條件判斷,ngClass動態(tài)樣式顯示
</div>
<br>
<div [ngClass]="color">
??根據(jù)變量值,自動進(jìn)行ngClass動態(tài)樣式顯示
</div>
<br>
<div [ngStyle]="{'color':color}">
??根據(jù)變量值,自動進(jìn)行ngStyle動態(tài)樣式顯示
</div>
雙向數(shù)據(jù)綁定
Mvvm:model層數(shù)據(jù)修改直接顯示到view層,view層數(shù)據(jù)修改直接更新到model層。model層是ts文件中定義的變量。
使用方法:
import {FormsModule} from '@angular/forms';
imports: [
??BrowserModule,
??FormsModule
],
public title:string='新聞組件';
<p>{{title}}</p>
雙向數(shù)據(jù)綁定修改標(biāo)題:<input type="text" [(ngModel)]="title">
public ?people:any = {
??name:'張三',
??sex:0,
??city:'鄭州',
??mark:'',
??cities:['上海','鄭州','北京'],
??hobby:[
????{title:'吃飯',
????checked:false},
????{title:'睡覺',
????checked:false},
????{title:'敲代碼',
????checked:true}
????]
};
<ul>
??<li>
????姓名:<input type="text" [(ngModel)]="people.name">
??</li>
??<li>
????性別:
????<!--男標(biāo)簽label是隱性綁定,女標(biāo)簽label是顯性綁定。for屬性規(guī)定label綁定的標(biāo)簽元素。點(diǎn)擊label標(biāo)簽就等于點(diǎn)擊綁定標(biāo)簽-->
????<label><input type="radio" value="1" id="man" [(ngModel)]="people.sex">男</label>
????<input type="radio" value="2" id="woman" [(ngModel)]="people.sex"><label for="woman">女</label>
??</li>
??<li>
????城市:
????<select [(ngModel)]="people.city">
??????<option *ngFor="let item of people.cities">{{item}}</option>
????</select>
??</li>
??<li>
????愛好:
????<label *ngFor="let item of people.hobby">
??????{{item.title}} <input type="checkbox" [(ngModel)]="item.checked">
????</label>
??</li>
??<li>
????備注:
????<textarea cols="30" rows="10" [(ngModel)]="people.mark"></textarea>
??</li>
</ul>
padding內(nèi)部距離-內(nèi)部寬、高;margin外部距離-距離左邊、右邊;span-行模塊;
注:angular中的數(shù)組foreach方法是異步
管道(Pipe)
管道是把數(shù)據(jù)作為輸入,然后將數(shù)據(jù)進(jìn)行格式化或轉(zhuǎn)換為其他,最后給出期望的輸出。比方說時間格式化。
<div>
??日期管道:{{today | date:'yyyy-MM-dd HH:mm:ss' | json}}
</div>
angular本身有一些內(nèi)置管道,像date(日期格式)、json(轉(zhuǎn)json字符串)等。
也可以自定義一些管道,然后通過{{變量 | 管道名}}的格式引用
獲取dom節(jié)點(diǎn)
ngOnInit獲取節(jié)點(diǎn)
<div id="div0" *ngIf="flag">
??angular條件顯示標(biāo)簽
</div>
flag:boolean = true;
ngOnInit(): void {
??/*組件和指令初始化完成,但是dom節(jié)點(diǎn)可能并沒有完全加載完成。
??例如:組件里HTML標(biāo)簽受指令控制是否顯示,這個標(biāo)簽在ngOnInit就獲取不到
??*/
??let div0:any = document.getElementById('div0');
??console.log(div0);
}
打印div0對象為null
獲取dom節(jié)點(diǎn)
獲取標(biāo)簽節(jié)點(diǎn),子組件節(jié)點(diǎn)
<div #mydiv id="div0" *ngIf="flag">
??angular條件顯示標(biāo)簽
</div>
flag:boolean = true;
@ViewChild("mydiv") mydiv :any;
ngAfterViewInit() {
??console.log('在ngAfterViewInit獲取div標(biāo)簽');
??console.log(this.mydiv);
}
<app-child-component #childComponent></app-child-component>
<button (click)="callChildRunFunction()">調(diào)用子組件方法</button>
@ViewChild("childComponent") childComponent:any;
callChildRunFunction(){
??this.childComponent.run();
}
run() {
??alert('子組件run方法');
}
父子組件通信
父組件給子組件傳值
msg:string = '父組件信息';
arr:any[]=[{name:'張三',age:18},{name:'李四',age:20}];
<!--在父組件中給子組件動態(tài)綁定屬性-->
<app-child-component #childComponent [msg]="msg" [arr]="arr"></app-child-component>
輸入父組件信息:<input type="text" [(ngModel)]="msg">
import { Component, OnInit,Input } from '@angular/core';
@Input() msg:any
@Input() arr:any;
<h2>從父組件接收到的信息:{{msg}}</h2>
<ul>
??<li *ngFor="let item of arr">
????{{item.name}} -- {{item.age}}
??</li>
子組件主動調(diào)用父組件方法
import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';
@Output() private outer = new EventEmitter<any>();
private product:any = {
??name:'牙膏',
??price:15
};
sendParent() {
??this.outer.emit(this.product);
}
<!--在父組件中給子組件動態(tài)綁定屬性-->
<app-child-component #childComponent [msg]="msg" [arr]="arr" (outer)="reciveFromChildMsg($event)"></app-child-component>
outer要與子組件定義的廣播對象命名一致
父組件主動調(diào)用子組件的數(shù)據(jù)和方法
父組件通過@viewChild
注意:非父子組件通信通過服務(wù)或Localstorage或cookie
組件生命周期
生命周期函數(shù)通俗的講就是組件創(chuàng)建、組件更新、組件銷毀的時候會觸發(fā)一系列的方法
ngOnChanges父子組件通信時,會觸發(fā).
之外,什么都不應(yīng)該做。 (非生命周期函數(shù))
ngOnInit?在 Angular 第一次顯示數(shù)據(jù)綁定和設(shè)置指令/組件的輸
入屬性之后,初始化指令/組件
ngAfterViewInit()
初 始 化 完 組 件 視 圖 及 其 子 視 圖 之 后 調(diào) 用 。 第 一
次 ngAfterContentChecked() 之后調(diào)用,只調(diào)用一次。
ngOnDestroy()
當(dāng) Angular 每次銷毀指令/組件之前調(diào)用并清掃。在這
兒反訂閱可觀察對象和分離事件處理器,以防內(nèi)存泄
漏。在 Angular 銷毀指令/組件之前調(diào)用
異步編程
常見異步編程的方法
Angular get請求
請求失敗且能捕獲異常
1、在 app.module.ts 中引入 HttpClientModule 并注入
import {HttpClientModule} from '@angular/common/http';
imports: [
BrowserModule,
HttpClientModule
]
2、在用到的地方引入 HttpClient 并在構(gòu)造函數(shù)聲明
import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient) { }
3、get 請求數(shù)據(jù)var api = "http://a.itying.com/api/productlist";
this.http.get(api).subscribe(response => {
console.log(response);
});
Angular post請求
1、在 app.module.ts 中引入 HttpClientModule 并注入
import {HttpClientModule} from '@angular/common/http';
imports: [
BrowserModule,
HttpClientModule
]
2、在用到的地方引入 HttpClient、HttpHeaders 并在構(gòu)造函數(shù)聲明 HttpClient
import {HttpClient,HttpHeaders} from "@angular/common/http";
constructor(public http:HttpClient) { }
3、post 提交數(shù)據(jù)const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
var api = "http://127.0.0.1:3000/doLogin";
this.http.post(api,{username:'張三',age:'20'},httpOptions).subscribe(response => {
console.log(response);
});
Angular jsonp請求
HttpclientJsonpModule.jsonp向服務(wù)端發(fā)送請求后,服務(wù)端可以調(diào)用回調(diào)函數(shù)(定義的本地函數(shù))來向前端返回數(shù)據(jù)
1、在 app.module.ts 中引入 HttpClientModule、HttpClientJsonpModule 并注入
import {HttpClientModule,HttpClientJsonpModule} from
'@angular/common/http';
imports: [
BrowserModule,
HttpClientModule,
HttpClientJsonpModule
]
2、在用到的地方引入 HttpClient 并在構(gòu)造函數(shù)聲明
import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient) { }
3、jsonp 請求數(shù)據(jù)
var api = "http://a.itying.com/api/productlist";
this.http.jsonp(api,'callback').subscribe(response => {
console.log(response);
});
Augular axios請求數(shù)據(jù)
httpclientmodule.get、httpclientmodule.post是否存在請求失敗函數(shù),異常捕獲。axios可以捕獲異常且有請求失敗函數(shù)
1、安裝 axios
cnpm install axios --save
2、用到的地方引入 axios
import axios from 'axios';
3、看文檔使用
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
路由
路由:根據(jù)URL匹配對應(yīng)的組件,動態(tài)將組件掛載到根組件上
路由配置
Ng new 項目名;創(chuàng)建項目的時候,創(chuàng)建路由。將創(chuàng)建的組件在app-routing.module.ts引用,并做訪問URL配置。
import { HomeComponent } from './components/home/home.component';
import { NewsComponent } from './components/news/news.component';
const routes: Routes = [
??{path:'home',component:HomeComponent},
??{path:'news',component:NewsComponent},
??/***匹配所有請求,存在請求找不到對應(yīng)的組件,默認(rèn)跳轉(zhuǎn)到home組件*/
??{path:'**',redirectTo:'home'}
];
<header class="header">
??<!--URL開頭是不是以/開頭都可以,建議都以/開頭-->
??<a href="home">首頁</a>
??<a routerLink="/news">新聞</a>
??<a routerLink="/other">其他</a>
</header>
<router-outlet></router-outlet>
如果路由以/開頭會報錯
{path:'/home',component:HomeComponent}
Get路由傳值
Get路由傳值將參數(shù)拼接到url后面。例如:/home?id=1,路由url=/home。[routerLink]="['/newscontent']" [queryParams]="{aid:key}"
{path:'home',component:HomeComponent},
id:any;
<a href="home?hid={{id}}" routerLinkActive="active">首頁1</a>
<a routerLink="/home" [queryParams]="{hid:id}" routerLinkActive="active">首頁2</a>
import { ActivatedRoute } from '@angular/router';
constructor(public router:ActivatedRoute) { }
ngOnInit(): void {
??this.router.queryParams.subscribe((data) => {
????this.id = JSON.stringify(data);
??})
}
動態(tài)路由傳值
動態(tài)路由將參數(shù)直接放到url里面,例如:路由url=/home/:id,id=1。/home/1;[routerLink]="[ '/newscontent/', key ]
<a routerLink="/detail/{{id}}" routerLinkActive="active">新聞詳情</a>
<a [routerLink]="['/detail/',id]">詳情2</a>
constructor(public router:ActivatedRoute) { }
ngOnInit(): void {
??this.router.params.subscribe((data)=>{
????console.log(data);
??})
}
JS跳轉(zhuǎn)-get路由傳值
???import { Router} from '@angular/router';
???constructor(public router:Router) { }
2、跳轉(zhuǎn)
this.router.navigate(['/news'],{
???queryParams:{
?????aid:123
???}
});
JS跳轉(zhuǎn)-動態(tài)路由傳值
1、引入聲明模塊
????
????import { Router} from '@angular/router';
????constructor(public router:Router) { }
?2、跳轉(zhuǎn)
???this.router.navigate(['/home']);
???this.router.navigate(['/newscontent/','1243'])
父子路由
總結(jié)
以上是生活随笔為你收集整理的Angular学习总结-入门篇的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Lattice PCIe 学习 1
- 下一篇: 信息流广告的发展前景!