Angular45

Angular 4 Tutorial for Beginners: Learn Angular 4 from Scratch     https://www.youtube.com/watch?v=k5E2AVpwsko&list=PLTjRvDozrdlxAhsPP4ZYtt3G8KbJ449oT
安裝Angular CLI: npm install -g @angular/cli   安裝以後輸入ng --version檢查版本.
建立新項目: ng new hello-world
打開vs code, 快捷鍵ctrol+shift+p,輸入code選擇Shell Command:Install 'code' command in PATH, 輸入code .(code後面空格而後是點)
ng server 啓動項目

安裝typescript: npm install -g typescript

javascript中var聲明的變量在它所屬最近的方法中都有效.e.g.
function doSomething(){
    for(var i=0;i<5;i++){
        console.log(i);
    }
    console.log('Finally: '+i);  //注意這裏的i也是有效的, 若是用typescript中的let定義變量i,則這裏的i無效.
}

強類型轉換: 
let endsWithC=(<string>message).endsWith('c');
let endsWithC=(message as string).endsWith('c');

typescript中方法的寫法:
let doLog=(message) => {console.log(message);} 相似於c#中的lamda寫法.

typescript不能含有多個構造函數, 若是須要實例化不帶參數的對象,則設置參數爲nullable.e.g.
constructor(x?: number, y?: number){
    this.x=x;
    this.y=y;
}

上面的寫法在typescript中能夠簡化爲:
constructor(public x?:number, private y?:number){

}

變量前能夠加private,public, protected修飾, 默認的是public.

屬性的例子:
變量x是私有的,
get X(){
    return this.x;
}

set X(value){
    if(value<0) throw new Error(''value cannot be less than 0.);
    this.x=value;
}
使用: let x=point.X;
point.X=10;

取名: course-4.component.ts
--------------------------------------------------------------------------------------------------------------------------------------------------------
Angular 4 - The Basics (Udemy Course Excerpt)     https://www.youtube.com/watch?v=htPYk6QxacQ
安裝Bootstrap命令:  npm install --save bootstrap
打開.angular-cli.json文件,在"style"節點下添加"../node_modules/bootstrap/dist/css/bootstrap.min.css"

selector:'app-servers' //元素
selector:'[app-servers]'  //屬性
selector:'.app-servers'  //類,不支持id

TODO: 1:10:0


-----------------------------------------------------------------------------------------------------------------------------------------------------
Angular 5 Tutorial - 1 - Introduction     https://www.youtube.com/watch?v=0eWrpsCLMJQ&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ
version 1.2.3  各數字分別表示  Major, Minor, Fix(Patch)
檢查版本:node -v, npm -v, ng -v(angular cli的版本)
AngularCLI官網: https:cli.angular.io   安裝命令:npm install -g @angular/cli

Angular 5 Tutorial - 3 - Hello World App   https://www.youtube.com/watch?v=mDoHtD1hI3I&index=3&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ
ng new hello-world --routing
cd hello-world
ng serve = npm start

selector的三種方式: 'app-test','.app-test','[app-test]', 對應的html爲<app-test></app-test>,<div class="app-test"></div>,<div app-test></div>

Angular 5 Tutorial - 6 - Property Binding   https://www.youtube.com/watch?v=N8FBmB2jme8&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=6
Attribute vs Property
Attribute - HTML
Properties - DOM (Document Object Model)
Attribute的值不變, Property的值可變.

Property Binding: [disabled]="isDisabled"  //1.左側是[],2.右側"",3.isDisabled是bool類型.
也能夠寫成:bind-disabled="isDisabled"

[class.text-danger]="hasError" //若是hasError爲true則應用樣式text-danger,否者不用
多條件: <h2 [ngClass]="messageClasses">Something</h2> //1.[ngClass] 2.messageClassess屬性包括多個條件

<h2 [style.color]="highlightColor">Style Binding</h2> //highlightColor是Property
<h2 [style.color]="'red'">Style Binding</h2>  //'red'
<h2 [style.color]="hasError ? 'red' : 'gree'">Style Binding</h2>
多條件: <h2 [ngStyle]="titleStyles">Style Binding 3</h2>  //titleStyles裏面有多個樣式設定

Angular 5 Tutorial - 9   https://www.youtube.com/watch?v=ZfIc1_oj7uM&index=9&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ
(click) = "onClick($event)" //帶event參數
(click) = "greeting='Hello World'"  //直接執行

<input #myInput type="text">
<button (click)="logMessage(myInput.value)">Log</button>

雙向綁定須要在app.module.ts中導入FormsModule
[(ngModel)]="name" 

*ngIf="isVisible" //不會顯示dom元素

Angular中的if else:
方法一:
<h2 *ngIf="displayName; else elseBlock">
    Codevolution
</h2>

<ng-template #elseBlock>
    <h2>
        Name is hidden
    </h2>
</ng-template>    
方法二:
<div *ngIf="displayName; then thenBlock; else elseBlock"></div>

<ng-template #thenBlock>
    <h2>aaa</h2>
</ng-template>        

<ng-template #elseBlock>
    <h2>bbb</h2>
</ng-template>        

Angular中的Switch:
<div [ngSwitch]="color">
    <div *ngSwitchCase="'red'">You picked red color</div>
    <div *ngSwitchCase="'blue'">You picked blue color</div>
    <div *ngSwitchCase="'green'">You picked green color</div>
    <div *ngSwitchDefault>Pick again</div>
</div>    

Angular中的for:
<div *ngFor="let color of colors; index as i">
    <h2>{{i}} {{color}}</h2>
</div>    

Angular 5 Tutorial - 15 - Component Interaction  https://www.youtube.com/watch?v=BGy8DdGw_WE&list=TLGG0JkcZDBvWZcxODEyMjAxNw
Parent > Child
app.component.html: <app-test [parentData]="name"></app-test>
test.component.ts: 
import {Input} from '@angular/core';  //導入命令空間Input
@Input() public parentData;  //@Input修飾符表示這個屬性是從父控件傳過來的, 別名的寫法: @Input('parentData') public name;

Parent > Child
test.component.ts:
import {Output,EventEmitter} from '@angular/core';  //導入命令空間
@Output() public childEvent = new EventEmitter();

<button (click)="fireEvent()">Send Event</button>
fireEvent(){
    this.childEvent.emit('Hello World');
}

app.component.html: <app-test (childEvent)="message=$event"></app-test> //這裏的$event就是子組件中傳過來的值'Hello World'

Angular 5 Tutorial - 16 - Pipes   https://www.youtube.com/watch?v=y8lwG8IM82k&index=2&list=TLGG0JkcZDBvWZcxODEyMjAxNw
{{name | slice:3:5}} //顯示從第三個字符開始到第五個字符(不包括)之間的字符
{{person | json}}
{{5.678 | number:'3.1-2'}}  //3表示小數點的左邊顯示三位數,1-2表示小數點的右邊顯示最少一位最多兩位數,最後顯示005.67
{{0.25 | currency}} //顯示$0.25
{{0.25 | currency: 'GBP'}}  //顯示英鎊
{{date | date:'short'}}
{{date | date:'shortDate'}}
{{date | date:'shortTime'}}

Angular 5 Tutorial - 21 - Fetch Data Using HTTP  https://www.youtube.com/watch?v=LmIsbzt-S_E&index=21&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ
ng g s employee 建立employee.service.ts
app.module.ts:
import {HttpClientModule} from '@angular/common/http';  //Angular5使用HttpClient而不是以前的Http
imports:[HttpClientModule]
employee.service.ts:
import {HttpClient} from '@angular/common/http';
constructor(private http:HttpClient){}
getEmployees():Observable<IEmployee[]>{ //須要指定返回結果爲Observable<IEmployee[]>
    return this.http.get<IEmployee[]>(this._url);
}

Angular 5 Tutorial - 22 - HTTP Error Handling  https://www.youtube.com/watch?v=TmTGQiLBS5A&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=22
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
getEmployees():Observable<IEmployee[]>{ 
    return this.http.get<IEmployee[]>(this._url)
    .catch(this.errorHandler);
}
errorHandler(error: HttpErrorResponse){
    return Observable.throw(error.message || "Server Error");
}

使用: this._employeeService.getEmployees().subscribe(data=>this.employees=data, error=>this.errorMsg=error);

Angular 5 Tutorial - 23 - Routing and Navigation  https://www.youtube.com/watch?v=Nehk4tBxD4o&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=23
ng new routing-demo --routing  //建立帶router的項目

如何在現有項目中添加router:
src/index.html: <base href="/">
添加app/app-routing.module.ts文件,導入到app.module.ts中.

ng g c department-list -it -is  //建立component

配置app-routing.module.ts:
export const routingComponents = [DepartmentListComponent, EmployeeListComponent], 導入到app.module.ts中. 以後有新的components只須要添加到app-routing.module.ts文件中.

<a routerLink="/departments" routerLinkActive="active">Departments</a>
<a routerLink="/employees" routerLinkActive="active">Employees</a>

npm start 啓動項目, 打開localhost:4200

Angular 5 Tutorial - 24 - Wildcard Route and Redirecting Routes   https://www.youtube.com/watch?v=QC6wRxXT26I&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=24
ng g c page-not-found -it -is   //建立component

app-routing.module.ts中添加:
{path:'', redirectTo:'/departments', pathMatch:'full'}  //放在最前,對應地址localhost:4200
{path:"**", component: PageNotFoundComponent}  //page not found必須放在最後

Angular 5 Tutorial - 25 - Route Parameters  https://www.youtube.com/watch?v=qh5nHv-4aw0&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=26
頁面跳轉, app-routing.module.ts:
import {DepartmentDetailComponent} from './department-detail/department-detail.component';
const routes:Routes=[
{path:'department/:id',component:DepartmentDetailComponent}
];
export const routingComponents=[DepartmentDetailComponent]

department-list.component.ts:
import {Router} from '@angular/router';
constructor(private router: Router){}
onSelect(department){
    this.router.navigate(['/departments',department.id]);
}


讀取url中傳過來的參數. department-detail.component.ts:
import {ActivatedRoute} from '@angular/router';
constructor(private route: ActivatedRoute){}
ngOnInit(){
    let id = parseInt(this.route.snapshot.paramMap.get('id'));
    this.departmentId = id;
}

Angular 5 Tutorial - 26 - paramMap Observable  https://www.youtube.com/watch?v=KRV9jZwl0Ig&index=25&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ         
route.snapshot有個缺點,當跳轉到同一個component只是參數有變化的時候,頁面裏面獲取的參數值不會改變. 這時須要使用route.paramMap來監視參數的變化:
import {ParamMap} from 'angular/router';
ngOnInit(){
    //let id = parseInt(this.route.snapshot.paramMap.get('id'));
    //this.departmentId = id;
    this.route.paramMap.subscribe((params:ParamMap)=>{        
        let id = parseInt(params.get('id'));
        this.departmentId = id;
    });
}

Angular 5 Tutorial - 27 - Optional Route Parameters  https://www.youtube.com/watch?v=gnTFkl2AF-w&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=27
用於跳轉回原地址,回到參數所表明的tab等
gotoDepartments(){
    let selectedId = this.departmentId ? this.departmentId : null;
    this.router.navigate(['/departments',{id: selectedId}]);  //點擊返回按鈕跳轉到地址 localhost:4200/departments;id=1, 這裏的;id=1便是可選參數
}
讀取可選參數id的值:
import {Router,ActivatedRoute,ParamMap} from '@angular/router';  
constructor(private router: Router, private route: ActivatedRoute){}
public selectedId;
ngOnInit(){
    this.route.paramMap.subscribe(()=>{
        let id = parseInt(params.get('id'));
        this.selectedId=id;
    });
}

Angular 5 Tutorial - 28 - Relative Navigation  https://www.youtube.com/watch?v=qktmk-7Kot8&index=28&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ  
this.router.navigate(['/departments', department.id]);  //絕對路徑
this.router.navigate([department.id],{relativeTo: this.route});  //相對路徑的寫法,department-list.component.ts中
this.router.navigate(['../',{id:selectedId}],{relativeTo: this.route});  //department-detail.components.ts中

Angular 5 Tutorial - 29 - Child Routes  https://www.youtube.com/watch?v=ZoeZxpfTCXk&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=29  //看完等更新
app-routing.module.ts:
{
    path:'departments/:id',
    component:DepartmentDetailComponent,
    children:[
        {path:'overview', component: DepartmentOverviewComponent},
        {path:'contact', component: DepartmentContactComponent}
    ]
}
//添加到routingComponents數組中
export const routingComponents = [DepartmentOverviewComponent,DepartmentContactComponent]

department-detail.component.ts:
<p>
    <button (click)="showOverview()">Overview</button>
    <button (click)="showContact()">Contact</button>
</p>
<router-outlet></router-outlet>
showOverview(){
    this.router.navigate(['overview'],{relativeTo: this.route});
}
showContact(){
    this.router.navigate(['contact'],{relativeTo: this.route});
}

















-----------------------------------------------------------------------------------------------------------------------------------------------------
Deploy An Angular App To Firebase In Minutes     https://www.youtube.com/watch?v=mF7FTWHS3ys
用windows自帶的命令窗口,不要用Gitbash.
打開firebase console頁面: https://console.firebase.google.com/ 點擊項目 > Hosting > Get started......

Javascript中的閉包:
Javascript語言的特殊之處,就在於函數內部能夠直接讀取全局變量。
另外一方面,在函數外部天然沒法讀取函數內的局部變量。  這裏有一個地方須要注意,函數內部聲明變量的時候,必定要使用var命令。若是不用的話,你實際上聲明瞭一個全局變量!
如何從外部讀取局部變量?那就是在函數的內部,再定義一個函數。
函數帶()纔是執行函數!
因爲在Javascript語言中,只有函數內部的子函數才能讀取局部變量,所以能夠把閉包簡單理解成「定義在一個函數內部的函數」。
閉包能夠用在許多地方。它的最大用處有兩個,一個是前面提到的能夠讀取函數內部的變量,另外一個就是讓這些變量的值始終保持在內存中。
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Use Babel & Webpack To Compile ES2015 - ES2017   https://www.youtube.com/watch?v=iWUR04B42Hc
babel_webpack_starter: https://github.com/bradtraversy/babel_webpack_starter
webpack: https://webpack.github.io/docs/what-is-webpack.html
Babel: https://babeljs.io

npm init //建立package.json文件,scripts下添加"build":"webpack", "start":"webpack-dev-server --output-public-path=/build/"
npm install --save-dev webpack webpack-dev-server babel-core babel-loader babel-preset-env
建立webpack.config.js
npm run build //編譯
npm start //啓動webpack-dev-server就不須要執行npm run build了, 它會一直監視修改不須要刷新頁面.

異步方法:
async function getPosts(){
    const response=await fetch('https://jsonplaceholder.typicode.com/posts');
    const data=await response.json();
    return data;
}
getPosts().then(posts=>console.log(posts));
npm install --save-dev babel-polyfill babel-preset-stage-0
修改webpack.config.js
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
01 Blank App In Visual Studio 2017  https://www.youtube.com/watch?v=2VIVOJsKrTI&list=PL2yYLRgebbHakhdiCZkykZQU0CQer3pvO
建立Empty的asp.net core項目, NuGet安裝Microsoft.AspNetCore.StaticFiles
安裝WebPack Task Runner 網址https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebPackTaskRunner, 打開 Task Runner Explorer 面板.
Add New Item > npm Configuration File 建立package.json並修改
Visual Studio的命令窗口是Pacage Manager Console.
package.json文件右鍵選擇Restore Packages,至關於執行命令npm install

Add New Item > TypeScript JSON Configuration File 建立 tsconfig.json文件並修改
Add New Item > WebPack Configuration File 建立 webpack.config.js文件並修改

index.ts文件中export全部的component和module.
import * as Barrel from '*'; //導入index.ts

執行AngularCLI命令編譯Angular程序: npm build
在開發的過程當中,咱們會用到AngularCLI命令中的 ng serve 命令來啓用Angular的監控服務模式。他會監控Angular的源碼變化,當源碼被改變時,自動從新編譯Angular程序並編譯TypeScript代碼。默認狀況下ng serve提供的是localhost:4200地址。
-----------------------------------------------------------------------------------------------------------------------------------------------------
Angular 4 CRUD With Web API   https://www.youtube.com/watch?v=Ous6v0r7kXc
Add New Item > 左側Data下的ADO.NET Entity Data Model取名DBModels
Add Controller > Web API 2 Controller with actions, useing Entity Framework  //仔細看下生成的代碼,頗有借鑑性.
後臺Post方法中不須要if(!ModelState.IsValid),全部的驗證在angular中.

ng new angularCURD  //建立angular項目
cd angularCURD
ng serve --open  //啓動服務並打開瀏覽器localhost://4200
生成的.spec.ts文件是用於測試的,能夠刪除.
ng g class employee.model 生成employee.model.ts文件.
app-emplloyees按下tab鍵,生成<app-emplloyees></app-emplloyees>
h2.jumbotron.bg-secondary.text-white按下tab鍵,生成<h2 class="jumbotron bg-secondary text-white"></h2>   //多個class之間用.
<input class="form-control" name="Office" #Office="ngModel" [(ngModel)]="employee" />  //#Office="ngModel"用於驗證

解決webapi跨域訪問的問題: 安裝組件Microsoft.AspNet.WebApi.Cors, 地址 https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors ,命令是Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.3 (或者Install-Package Microsoft.AspNet.WebApi.Cors) 以後代碼:
using System.Web.Http.Cors;
[EnableCors(origins: "http://localhost:4200",headers:"*",methods:"*")]    //加到public class EmployeeControler: ApiController之上
上面是針對指定controller, 加到WebApiConfig.cs文件的Register方法下能夠針對整個項目有效.
頁面報錯的話執行代碼Install-Package Microsoft.AspNet.WebApi.Core -Version 5.2.3

安裝toastr插件: npm install ngx-toastr --save, 地址https://www.npmjs.com/package/ngx-toastr,
.angular-cli.json中的"styles"節點下添加"../node_modules/ngx-toastr/toastr.css"
app.modules.ts中:
import {ToastrModule} from 'ngx-toastr';
imports:[
    ToastrModule.forRoot()
]
emplloyees.component.ts中:
import {ToastrService} from 'ngx-toastr'
constructor(private toastr:ToastrService)
this.toastr.success('New Record Added Successfully','Employee Register')

showForEdit(emp: Employee)
{
    this.employeeService.selectedEmployee = Object.assign({},emp);
}
-----------------------------------------------------------------------------------------------------------------------------------------------------
Angular And Contentful - Content Management For Single-Page Web Apps   https://www.youtube.com/watch?v=KhmjLjvlmyQ
Contentful官網: https://www.contentful.com
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息