Angular4的學(xué)習(xí)

2018-3-15 星期四

一、安裝

注意:請現(xiàn)在終端/控制臺窗口中運行 node -v 和 npm -v,來驗證一下你正在運行的 node 6.9.x 和 npm 3.x.x 以上的版本。更老的版本可能會出現(xiàn)錯誤,更新的版本則沒問題。

全局安裝 Angular CLI 腳手架工具(只需安裝一次)

1.使用 npm 命令安裝

npm install -g @angular/cli

注意:這里的@angular/cli版本為:

image.png

2.安裝 cnpm

npm install -g cnpm --registry=https://registry.npm.taobao.org

3.使用 cnpm 命令安裝

cnpm install -g @angular/cli

創(chuàng)建項目

1.打開 cmd 找到要創(chuàng)建項目的目錄
2.創(chuàng)建項目

ng new 項目名稱 eg: ng new my-app

3.創(chuàng)建帶路由的項目

ng new 項目名稱 --routing

3.進(jìn)入剛才創(chuàng)建的項目里面啟動服務(wù)

cd my-app
ng serve --open //啟動服務(wù)(--open可以省略)

安裝插件(jquery/bootstrap......)

方法一:

npm install jquery --save
npm install bootstrap --save

方法二:

npm install bootstrap@4.0.0-alpha.6 jquery tether --save

配置項目中的.angular-cli.json文件:
style:[
??"style.css",
??"../node_modules/bootstrap/dist/css/bootstrap.css"
],
script:[
??"../node_modules/jquery/dist/jquery.js",
??"../node_modules/bootstrap/dist/bootstrap.js"
]
方法一需要:讓typescript能解析文件:
npm install @types/jquery --save-dev
npm install @types/bootstrap --save-dev

在angular4中使用sass

1、利用npm工具安裝sass依賴和loader

npm install node-sass --save-dev
npm install sass-loader --save-dev

2、修改.angular-cli.json文件

"styles": [
    "styles.scss"
],
"defaults":{
    "styleExt": "scss",
    "component": {}
}

注意:不用懷疑是不是寫錯了,不是sass,就是改成scss

3、將項目中已經(jīng)存在的.css文件改成.scss【項目會自動修改的】

4、新建的component項目會直接生成.scss文件

創(chuàng)建組件

ng g c components/組件名 eg:ng g c components/navbar

注意:ng g component my-new-component是創(chuàng)建一個新的組件,默認(rèn)創(chuàng)建在src/app目錄下;ng g component components/my-new-component是創(chuàng)建到指定目錄下面
使用組件:在 app.component.html 中添加組件的 component.ts 中 @Component 中 selector 后面的值為標(biāo)簽名的標(biāo)簽(參見頁面底部)

如:navbar 組件中的 navbar.component.ts中有
@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
那這個組件在主頁面中使用時為:
<app-navbar></app-navbar>
主要組件介紹:
import { BrowserModule } from '@angular/platform-browser';/*瀏覽器解析的模塊*/
import { NgModule } from '@angular/core';/*angular.js 核心模塊*/
import { FormsModule } from '@angular/forms';/*表單數(shù)據(jù)綁定 表單驗證需要的模塊*/
import { AppComponent } from './app.component';/*根組件*/
import { HttpModule } from '@angular/http';/*數(shù)據(jù)請求模塊*/

@NgModule({
  declarations: [    /*引入當(dāng)前項目運行的組件*/
    AppComponent,
  ],
  imports: [      /*引入當(dāng)前模塊運行依賴的其他模塊*/
    BrowserModule,
    FormsModule
  ],
  providers: [DataService],      /*定義的服務(wù)*/
  bootstrap: [AppComponent]      /*指定應(yīng)用的主視圖(稱為根組件)通過引導(dǎo)根 AppModule 來啟動應(yīng)用,這里一般寫的是根組件*/

export class AppModule { }  /*根模塊不需要導(dǎo)出任何東西,因為其他組件不需要導(dǎo)入根模塊,但是一定要寫*/
})
創(chuàng)建服務(wù)

ng g s services/服務(wù)名 eg:ng g s services/data

注意:創(chuàng)建服務(wù)后npm沒有幫我們將服務(wù)自動添加到app.module.ts中,需要我們手動添加

在app.module.ts中添加import { DataService } from './services/data.service';
然后將 DataService 添加到providers中:providers: [DataService],


創(chuàng)建路由

一:直接創(chuàng)建一個配置好路由的項目

1、首先使用 ng new demo02 --routing 命令創(chuàng)建新的項目
2、引入組件,然后

假設(shè)有三個頁面:主頁面home、新聞頁面news、新聞詳情頁newscontent
ng g c components/home
ng g c components/news
ng g c components/newscontent

3、找到app-routing.module.ts配置路由

import { HomeComponent } from './components/home/home.component'; 
import { NewsComponent } from './components/news/news.component'; 
import { NewscontentComponent } from './components/newscontent/newscontent.component'; 

const routes: Routes = [
 {path:'home',component:HomeComponent},
 {path:'news',component:NewsComponent},
 {
  path:'newscontent/:id',/*配置動態(tài)路由*/
  component:NewscontentComponent
 },
 {
  path: '',
  redirectTo: 'home',
  pathMatch: 'full'
 },
 {/*匹配不到路由的時候加載的組件*/
  path: '**',/*任意的路由*/
  redirectTo: 'home'
 }
];

4、找到 app.component.html 根組件模板,配置 router-outlet 顯示動態(tài)加載的路由

<h1>
  <!-- routerLinkActive  為選中路由加載相應(yīng)的class(激活樣式)如果routerLinkActive寫在a鏈接的父類中,那么在路由到相應(yīng)的頁面時,它的父類就會獲得激活樣式 -->
  <a routerLink="/home" routerLinkActive="active">首頁</a>
  <a routerLink="/news" routerLinkActive="active">新聞</a>
</h1>

<hr>
<router-outlet></router-outlet>
image.png

二、在已經(jīng)創(chuàng)建好的項目中添加路由

1、假設(shè)已經(jīng)有相應(yīng)的模塊:home、news、newscontent
2、在app文件夾下新建app-routing.module.ts頁面,并向其中注入模塊+引入組件+配置組件+配置模塊+暴露模塊

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './components/home/home.component';
import { NewsComponent } from './components/news/news.component';
import { NewscontentComponent} from './components/newscontent/newscontent.component';

const routes: Routes = [
 {
  path:'home',
  component:HomeComponent
 },
 {
  path:'news',
  component:NewsComponent
 },
 {
     /*:id  配置動態(tài)路由*/
  path:'newscontent/:id',
  component:NewscontentComponent
 },
 {
  path: '',
  redirectTo: 'home',
  pathMatch: 'full'
 },
 {/*匹配不到路由的時候加載的組件*/
  path: '**',/*任意的路由*/
  redirectTo: 'home'
 }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule{ }

3、在 app.module.ts 中引入剛才定義的路由
import { AppRoutingModule } from './app-routing.module';
4、app.module.ts 里面的 import 注冊這個路由模塊

imports: [
   BrowserModule,
   AppRoutingModule
]

5、找到 app.component.html 根組件模板,配置 router-outlet 顯示動態(tài)加載的路由

<h1>
  <!-- routerLinkActive  為選中路由加載相應(yīng)的class(激活樣式) -->
  <a routerLink="/home" routerLinkActive="active">首頁</a>
  <a routerLink="/news" routerLinkActive="active">新聞</a>
</h1>

<hr>
<router-outlet></router-outlet>

路由的動態(tài)傳值
1、配置動態(tài)路由,上文有(:id)
2、獲取動態(tài)路由的值

注意:那個頁面需要動態(tài)路由,在哪個頁面引入
import { ActivatedRoute } from '@angular/router';


constructor(private route:ActivatedRoute) { }

 ngOnInit() {
  //獲取動態(tài)路由
  console.log(this.route.params['_value'].id)
  或者:使用this.route.params.subscribe(data=>this.id=data.id);
 }

1、
image.png

2、
image.png

image.png


創(chuàng)建管道

ng g pipe 管道名 eg:ng g pipe my-new-pipe 或者 ng g p my-new-pipe 類似寫法相同

創(chuàng)建類

ng g class my-new-class

創(chuàng)建指令

ng g directive my-new-directive

創(chuàng)建Guard

ng g guard my-new-guard

創(chuàng)建interface

ng g interface my-new-interface

創(chuàng)建enum

ng g enum my-new-enum

創(chuàng)建module

ng g module my-module

父子組件之間的傳遞和引用

1、嵌套

組件之間的嵌套和在主頁面中引用組件的方式一樣,找到子組件的selector,然后在父組件的頁面中引用標(biāo)簽名,例:
<app-question *ngFor="let question of questions"></app-question>

2、子組件引用父組件的數(shù)據(jù)

傳遞數(shù)據(jù)需要在父組件中設(shè)定屬性,給屬性賦值:
<app-question *ngFor="let question of questions" [question]="question"></app-question>
然后子組件的component.ts中添加依賴 Input :
import { Component, OnInit, Input } from '@angular/core';
再在函數(shù)中添加 @Input 接收父組件中被賦值的屬性:
@Input("question") question:Question;



Angular的一些指令

*ngFor普通循環(huán)
<ul>
    <li *ngFor="let item of list">{{item}}</li>
</ul>

循環(huán)的時候設(shè)置key

<ul>
  <li *ngFor="let item of list;let i = index">{{item}} --{{i}}</li>
</ul>
或者:
<ul>
  <li *ngFor="let item of list;index as i">{{item}}---{{i}}</li>
</ul>

template循環(huán)數(shù)據(jù)

<ul>
  <li template="ngFor let item of list">{{item}}</li>
</ul>
*ngIf 條件判斷
<p *ngIf="list.length > 3">這是 ngIf 判斷是否顯示</p>
<p template="ngIf list.length > 3"> 這是 ngIf 判斷是否顯示</p>
(click)="getDate()" 執(zhí)行事件
<button class="button (click)="getData()">點擊按鈕觸發(fā)事件</button>
button class="button" (click)="setData()">點擊按鈕設(shè)置數(shù)據(jù)</button>
etData(){/*自定義方法獲取數(shù)據(jù)*/ //獲取alert(this.msg)};
setData(){//設(shè)置值 this.msg="這是設(shè)置的值";}
綁定屬性

使用[屬性]=“值”進(jìn)行屬性綁定(屬性如果不加[],那么就直接是傳統(tǒng)的賦值,加上[]就是angular中屬性綁定)

<!-- 例子 -->
<p>2.屬性綁定:</p>
<img src="{{src}}"/>
<p>3.屬性綁定:</p>
<img [src]="src"/>

<!-- ts -->
src:string = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
class類的綁定

1、直接使用[class]DOM綁定會覆蓋之前的class

<div class="a b" [class]="classname"></div>
//ts文件
classname:string = "c";

2、使用[class.類名]=”boolean”來判斷是否追加這個class

<div class="a b" [class.c]="isShow"></div>
// 或者使用表達(dá)式
<div class="a b" [class.c]="isShow == true"></div>
//ts文件
isShow:boolean = true;

3、使用對象顯示

<div [ngClass]={a:isA,b:isB,c:isC}></div>
//ts文件
isA:boolean = true;
isB:boolean = true;
isC:boolean = true;
//或者
<div [ngClass]="classGroup"></div>
//ts文件
classGroup:any = {
    a:true,
    b:true,
    c:true
  }
樣式綁定

1、綁定單個樣式

<p [style.color]="isRed?'red':'blue'">我是測試樣式的</p>
<p [style.color]="redColor">我是測試樣式的</p>
// ts文件
isRed:boolean = true;
redColor:string = "red";

2、帶單位的

<p [style.font-size.em]="fontSize?1:3">我是測試樣式的</p>
// ts
fontSize:boolean = false;

3、綁定多個樣式

<div [ngStyle]="styleGroup"></div>
// ts
styleGroup:any = {
  width:"100px",
  height:"100px",
  border:"1px solid #ddd",
  margin:"20px"
}
綜合運用的一次示例

在for循環(huán)中使用屬性綁定和事件綁定:

<!-- html -->
  <div class="my-list" *ngFor="let item of typeList;index as i" (click)="item.ev()" [class.list3]="i == 2">
    <div>
      <ion-icon name="{{item.icon}}" [style.color]="item.color"></ion-icon>
      {{item.name}}
    </div>
    <ion-icon name="ios-arrow-forward"></ion-icon>
  </div>
.my-list{
    display: flex;
    justify-content: space-between;
    padding: 11px 30px 11px 20px; 
    font-size: 16px;
    color: #333;
    border-top: 1px solid #eee;
    div{
      width: 150px;
      ion-icon{
        margin-right: 13px;
      }
    }
    &.list3{
      border-bottom: 1px solid #eee;
    }
 }
// ts
typeList = [
    {
      ev: ()=>{this.hello()},
      icon: 'star',
      color: '#63c860',
      name: '投放記錄',
    },
    {
      ev: ()=>{this.world()},
      icon: 'ios-clock',
      color: '#7699ff',
      name: '我的積分'
    },
    {
      ev: ()=>{ this.name()},
      icon: 'ios-home',
      color: '#ffd700',
      name: '兌換記錄'
    }
];
constructor(...){...}
hello(){
  console.log('hello');
}
world(){
  console.log('world');
}
name(){
  console.log('xiao ming');
}
表單處理
<input type="test" (keyup)="keyUpFn($event)"/>
keyUpFn(e){console.log(e)}
雙向數(shù)據(jù)綁定
<input [(ngModel)]="inputValue">
注意引入:FormsModule
import { FormsModule } from '@angular/forms';
@NgModule({
    declarations:[
       AppComponent,
       HeaderComponent,
       FooterCompoonent,
       NewsComponent
   ],
  imports:[
      BrowserModule,
      FormsModule
  ],
  providers: [],
    bootstrap: [AppComponent]
})
export class AppModule{   }

使用

<input type="text" [(ngModel)]="inputValue"/>
{{inputValue}}
Todolist 功能

html部分

<input type="text" [(ngModel)]="username">
<button (click)='addData()>增加</button>
<ul>
   <li *ngFor="let item of list>{{item}}</li>
</ul>

js部分

export class TodolistComponent implements OnInit {
  list:any[];
  username:any;
  
  consturctor(){

  }
  
  ngOnInit(){
    this.list=[];
    this.username='';
  }
  addData(){
    alert(this.username);
    this.list.push(this.username);
  }

}

其他的一些內(nèi)容

import { Component, OnInit } from '@angular/core';    /*引入 angular 核心*/

@Component({
  selector: 'app-question-list',    /*使用這個組件的名稱*/
  templateUrl: './question-list.component.html',    /*html模板*/
  styleUrls: ['./question-list.component.css']    /*css 樣式*/
})
export class QuestionListComponent implements OnInit {

  constructor() {   }    /*構(gòu)造函數(shù)*/

  ngOnInit() {      /*初始化加載的生命周期函數(shù)*/
   
  }
}

關(guān)于打包

1、執(zhí)行打包命令:ng build --prod --aot后會生成dist文件,但有可能打包出來的文件里面的index.html什么都不顯示,解決辦法:

將項目/src 目錄下的index.html內(nèi)容修改:
<base href="/"> 修改為
<base href="./"> 即可。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AdminConsole</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>

2、將項目發(fā)布到服務(wù)器上后圖片路徑都為assets/.......或者./assets/.....
3、項目發(fā)布到服務(wù)器刷新顯示404問題:
解決方法:
配置app.module.ts

import {HashLocationStrategy , LocationStrategy} from '@angular/common';

@NgModule({
  declarations: [AppCmp],
  bootstrap: [AppCmp],
  imports: [BrowserModule, routes],
  providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
});

主要添加的代碼:
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
這樣設(shè)置后,訪問angular站點,會自動在根節(jié)點后面加一個#錨點。再次刷新便不會報404錯誤了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容