天天看點

Angular學習總結-入門篇一、 Angular介紹六、Angular開發工具介紹Angular項目結構介紹建立元件/服務angular文法

目錄

一、 Angular介紹 

二、 學習Angular必備基礎 

三、 Angular環境搭建 

四、 Angular建立項目 

五、 Angular環境搭建以及建立項目的時候可能遇到的錯誤 

六、Angular開發工具介紹 

Angular項目結構介紹 

建立元件/服務 

angular文法 

變量 

ngFor循環+ngIf判斷+ngSwitch 

動态修改樣式ngClass+ngStyle 

雙向資料綁定 

管道(Pipe) 

擷取dom節點 

ngOnInit擷取節點 

擷取dom節點 

父子元件通信 

父元件給子元件傳值 

子元件主動調用父元件方法 

父元件主動調用子元件的資料和方法 

元件生命周期 

異步程式設計 

Angular get請求 

Angular post請求 

Angular jsonp請求 

Augular axios請求資料 

路由 

路由配置 

Get路由傳值 

動态路由傳值 

JS跳轉-get路由傳值 

JS跳轉-動态路由傳值 

父子路由 

一、 Angular介紹

Angular是谷歌開發的一款開源的web前端架構,誕生于2009年,由Misko Hevery 等人建立,後為Google所收購。是一款優秀的前端JS架構,已經被用于Google的多款産品當中。

根據項目數統計angular(1.x 、2.x 、4.x、5.x、6.x、7.x 、8.x、9.x)是現在網上使用量最大的架構。

Angular基于TypeScript和react、vue相比 Angular更适合中大型企業級項目。

目前2019年12月25日angular最新版本angular9.x。根據官方介紹,Angular每過幾個月就會更新一個版本。Angular2.x以後所有的Angular版本用法都是一樣的,此教程同樣适用于Angular7.x 、Angular8.x、Angular9.x 以及未來的其它版本....。

正在上傳…重新上傳取消

Angular學習總結-入門篇一、 Angular介紹六、Angular開發工具介紹Angular項目結構介紹建立元件/服務angular文法

null

  • 學習Angular必備基礎

必備基礎:html  、css 、js、es6

如果有Typescript基礎更容易了解,沒有Typescript基礎也可以學此教程。此教程中用到的Typescript文法會詳細講解。

Typescript基礎入門教程: TypeScript視訊教程免費下載下傳-6小時學會TypeScript入門實戰-IT營大地2020年更新_IT營

  • Angular環境搭建

1、安裝前準備工作:

1.1、安裝nodejs

Node.js (nodejs.org)   通路該網站下載下傳穩定版本的msi安裝包

修改安裝路徑

安裝結束後,通過node -v檢視node版本

Npm -v檢視npm版本   npm包管理器

npm install -g  下載下傳全局包時會有個預設存放路徑,預設存放路徑檢視指令: npm root -g

一般預設路徑是:C:\Users\使用者名\AppData\Roaming\npm\node_modules

設定存放路徑:

npm config set prefix "F:\packages\node_global"

npm config set cache "F:\packages\node_cache"

Npm config list

做環境變量配置:

Angular學習總結-入門篇一、 Angular介紹六、Angular開發工具介紹Angular項目結構介紹建立元件/服務angular文法
Angular學習總結-入門篇一、 Angular介紹六、Angular開發工具介紹Angular項目結構介紹建立元件/服務angular文法

安裝angular的計算機上面必須安裝最新的nodejs--注意安裝nodejs穩定版本

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驗證安裝是否成功

  • Angular建立項目
  1. 打開指令行工具找到你要建立項目的目錄
  1. 建立項目

ng new 項目名稱   

不能使用cnpm安裝angular/cli  

直接安裝:

ng new angulardemo  --同時會安裝依賴包,執行的指令就是npmi

如果要跳過npm i安裝:

ng new angulardemo --skip-install --不需要安裝依賴包

進入到angulardemo 目錄下,執行cnpm install 下載下傳依賴包。如果不下載下傳依賴包,執行運作程式會報錯

  1. 運作項目

cd angulardemo

ng serve --open

  • Angular環境搭建以及建立項目的時候可能遇到的錯誤
  1. npm安裝angular/cli失敗

解決方案:用 cnpm 安裝

  1. 建立項目npm i的時候失敗

解決方案1:ctrl+c結束項目,cd到項目裡面,用 cnpm i 安裝依賴

解決方案2:建立項目的時候  --skip-install

ng new my-app --skip-install

cd my-app

cnpm install   /   yarn

  1. 建立項目後用npm i 或者 cnpm i後項目沒法運作

解決方案:用yarn 替代 cnpm和npm

1 cnpm instal @angular/cli (我的npm會報錯);

2 ng new 的時候阻止自動安裝ng包,隻建立ng目錄     

ng new my-app --skip-install

3 安裝yarn        npm install -g yarn   /       cnpm install -g yarn   

4 進入目錄my-app 使用yarn 安裝ng所依賴的包          yarn

注意:yarn 指令 等同于  npm install / cnpm install       使用yarn前提是先安裝yarn  ,安裝使用 cnpm install -g yarn   就可以安裝

六、Angular開發工具介紹

1.Webstorm

2.Visual Studio Code

Visual Studio Code - Code Editing. Redefined

安裝插件

Angular項目結構介紹

  1. App.module.ts:根子產品-告訴angular應用包含的元素都有什麼,定義出聲明的元件集合-declarations、引用的子產品集合-imports、提供的服務集合-providers。
  1. App.component.*:根元件。ts檔案是定義變量、函數;css檔案是定義界面樣式;html是定義界面布局。每個元件都要包含這3部分。其他元件的頁面展示需要挂載到app.component.html才能展示。

挂載方式:

      1. 引用元件的selector:<app-products></app-products>
      2. 通過路由引用:

建立元件/服務

建立元件: ng g component components/news

建立服務: ng g service services/storage

服務沒法調用元件裡的方法,元件之間也不能互相調用方法(除父子元件外)

建立服務:

ng g service services/storage

在服務ts檔案裡建立方法

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],

在具體元件中引用及調用服務接口

import {StorageService} from "../../services/storage.service";

constructor(public storageService:StorageService) { }

doSubmit() {

  this.storageService.set(this.people.name,this.people);

}

angular文法

變量

  1. 變量定義:在元件ts檔案中定義變量,

格式:[通路權限] 變量名 [:資料類型] =’指派’;

      Public title:string=’我是一個标題’;

通路權限預設是public,建議每個變量都加上對應的資料類型

  1. 變量引用:在html引用變量

綁定屬性:

<img src="assets/images/02.png" alt="收藏" />

<img [src]="picUrl" />

動态屬性綁定記得用[]中括号

ngFor循環+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()" > 男

動态修改樣式ngClass+ngStyle

color:string='green';

flag:boolean = false;

.red {

  color: red;

}

.blue {

  color:blue;

}

.green {

  color:green;

}

<div class="red">

  靜态樣式

</div>

<br>

<div [ngClass]="{'red':flag,'blue':!flag}">

  條件判斷,ngClass動态樣式顯示

</div>

<br>

<div [ngClass]="color">

  根據變量值,自動進行ngClass動态樣式顯示

</div>

<br>

<div [ngStyle]="{'color':color}">

  根據變量值,自動進行ngStyle動态樣式顯示

</div>

雙向資料綁定

Mvvm:model層資料修改直接顯示到view層,view層資料修改直接更新到model層。model層是ts檔案中定義的變量。

使用方法:

  1. 首先在app.module.ts檔案中引入FormsModule

import {FormsModule} from '@angular/forms';

imports: [

  BrowserModule,

  FormsModule

],

  1. 在需要用到雙向資料綁定的元件的html中引入[(ngModel)]

public title:string='新聞討論區件';

<p>{{title}}</p>

雙向資料綁定修改标題:<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>

    性别:

    <!--男标簽label是隐性綁定,女标簽label是顯性綁定。for屬性規定label綁定的标簽元素。點選label标簽就等于點選綁定标簽-->

    <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内部距離-内部寬、高;margin外部距離-距離左邊、右邊;span-行子產品;

注:angular中的數組foreach方法是異步

管道(Pipe)

管道是把資料作為輸入,然後将資料進行格式化或轉換為其他,最後給出期望的輸出。比方說時間格式化。

<div>

  日期管道:{{today | date:'yyyy-MM-dd HH:mm:ss' | json}}

</div>

angular本身有一些内置管道,像date(日期格式)、json(轉json字元串)等。

也可以自定義一些管道,然後通過{{變量 | 管道名}}的格式引用

擷取dom節點

ngOnInit擷取節點

<div id="div0" *ngIf="flag">

  angular條件顯示标簽

</div>

flag:boolean = true;

ngOnInit(): void {

  let div0:any = document.getElementById('div0');

  console.log(div0);

}

列印div0對象為null

擷取dom節點

擷取标簽節點,子元件節點

  1. 通過原生的document.getElementById('div0')擷取
  2. 通過ViewChild擷取dom節點

<div #mydiv id="div0" *ngIf="flag">

  angular條件顯示标簽

</div>

flag:boolean = true;

@ViewChild("mydiv") mydiv :any;

ngAfterViewInit() {

  console.log('在ngAfterViewInit擷取div标簽');

  console.log(this.mydiv);

}

  1. 通過ViewChild擷取子元件,并調用子元件方法

<app-child-component #childComponent></app-child-component>

<button (click)="callChildRunFunction()">調用子元件方法</button>

@ViewChild("childComponent") childComponent:any;

callChildRunFunction(){

  this.childComponent.run();

}

run() {

  alert('子元件run方法');

}

父子元件通信

父元件給子元件傳值

  1. 在父元件引用的子元件中動态綁定屬性

msg:string = '父元件資訊';

arr:any[]=[{name:'張三',age:18},{name:'李四',age:20}];

<!--在父元件中給子元件動态綁定屬性-->

<app-child-component #childComponent [msg]="msg" [arr]="arr"></app-child-component>

輸入父元件資訊:<input type="text" [(ngModel)]="msg">

  1. 在子元件中通過@Input擷取父元件傳的值

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>

子元件主動調用父元件方法

  1. 在子元件中定義廣播執行個體對象,并編寫廣播方法

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);

}

  1. 父元件監聽子元件的廣播執行個體對象,

<!--在父元件中給子元件動态綁定屬性-->

<app-child-component #childComponent [msg]="msg" [arr]="arr" (outer)="reciveFromChildMsg($event)"></app-child-component>

outer要與子元件定義的廣播對象命名一緻

父元件主動調用子元件的資料和方法

父元件通過@viewChild

注意:非父子元件通信通過服務或Localstorage或cookie

元件生命周期

生命周期函數通俗的講就是元件建立、元件更新、元件銷毀的時候會觸發一系列的方法

ngOnChanges父子元件通信時,會觸發.

  1. constructor 構造函數中除了使用簡單的值對局部變量進行初始化

之外,什麼都不應該做。 (非生命周期函數)

ngOnInit 在 Angular 第一次顯示資料綁定和設定指令/元件的輸

入屬性之後,初始化指令/元件

ngAfterViewInit()

初 始 化 完 組 件 視 圖 及 其 子 視 圖 之 後 調 用 。 第 一

次 ngAfterContentChecked() 之後調用,隻調用一次。

ngOnDestroy()

當 Angular 每次銷毀指令/元件之前調用并清掃。在這

兒反訂閱可觀察對象和分離事件處理器,以防記憶體洩

漏。在 Angular 銷毀指令/元件之前調用

異步程式設計

常見異步程式設計的方法

    1. 回調函數
    2. Promise
    3. Rxjs

Angular get請求

請求失敗且能捕獲異常

1、在 app.module.ts 中引入 HttpClientModule 并注入

import {HttpClientModule} from '@angular/common/http';

imports: [

BrowserModule,

HttpClientModule

]

2、在用到的地方引入 HttpClient 并在構造函數聲明

import {HttpClient} from "@angular/common/http";

constructor(public http:HttpClient) { }

3、get 請求資料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 并在構造函數聲明 HttpClient

import {HttpClient,HttpHeaders} from "@angular/common/http";

constructor(public http:HttpClient) { }

3、post 送出資料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向服務端發送請求後,服務端可以調用回調函數(定義的本地函數)來向前端傳回資料

1、在 app.module.ts 中引入 HttpClientModule、HttpClientJsonpModule 并注入

import {HttpClientModule,HttpClientJsonpModule} from

'@angular/common/http';

imports: [

BrowserModule,

HttpClientModule,

HttpClientJsonpModule

]

2、在用到的地方引入 HttpClient 并在構造函數聲明

import {HttpClient} from "@angular/common/http";

constructor(public http:HttpClient) { }

3、jsonp 請求資料

var api = "http://a.itying.com/api/productlist";

this.http.jsonp(api,'callback').subscribe(response => {

console.log(response);

});

Augular axios請求資料

httpclientmodule.get、httpclientmodule.post是否存在請求失敗函數,異常捕獲。axios可以捕獲異常且有請求失敗函數

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

});

路由

路由:根據URL比對對應的元件,動态将元件挂載到根元件上

路由配置

Ng new 項目名;建立項目的時候,建立路由。将建立的元件在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},

  {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路由傳值将參數拼接到url後面。例如:/home?id=1,路由url=/home。[routerLink]="['/newscontent']" [queryParams]="{aid:key}"

  1. 跳轉

{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>

  1. 接收傳值

import { ActivatedRoute } from '@angular/router';

constructor(public router:ActivatedRoute) { }

ngOnInit(): void {

  this.router.queryParams.subscribe((data) => {

    this.id = JSON.stringify(data);

  })

}

動态路由傳值

動态路由将參數直接放到url裡面,例如:路由url=/home/:id,id=1。/home/1;[routerLink]="[ '/newscontent/', key ]

  1. 跳轉

<a routerLink="/detail/{{id}}" routerLinkActive="active">新聞詳情</a>

<a [routerLink]="['/detail/',id]">詳情2</a>

  1. 傳值

constructor(public router:ActivatedRoute) { }

ngOnInit(): void {

  this.router.params.subscribe((data)=>{

    console.log(data);

  })

}

JS跳轉-get路由傳值

  1. 引入聲明子產品

       import { Router} from '@angular/router';

       constructor(public router:Router) { }

2、跳轉

this.router.navigate(['/news'],{

   queryParams:{

     aid:123

   }

});

JS跳轉-動态路由傳值

1、引入聲明子產品

    import { Router} from '@angular/router';

    constructor(public router:Router) { }

 2、跳轉

   this.router.navigate(['/home']);

   this.router.navigate(['/newscontent/','1243'])

父子路由

繼續閱讀