本文章宗旨在於快速開始angular開發,或者快速瞭解angular開發注意事項的文章javascript
若是安裝腳手架報錯,強制清理npm緩存後從新安裝css
當你下載好官方案列後,你可能對目錄都不太熟悉,先不要將關注點放在這裏,文章致力於如何快速上手一個angular項目。html
表達式中的上下文變量是由如下三種組成:java
當存在相同的表達式變量優先順序:模板變量>>指令的上下文變量>>組件的成員變量npm
import { Component } from '@angular/core';
//my-app/src/app/app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private data0:Number = 1121;
data1 = '<div>dddddd</div>';
data2 = {
aaa:222
};
data3(){
};
data4 = null;
data5 = undefined;
data6 = [1,2,3]
}
複製代碼
<div>
<div>data0 :{{data0}}</div>
<div>data1 :{{data1}}</div>
<div>data2 :{{data2}}</div>
<div>data3 :{{data3}}</div>
<div>data4 :{{data4}}</div>
<div>data5 :{{data5}}</div>
<div>data6 :{{data6}}</div>
<div>data7 :{{data7}}</div>
</div>
<!-- data0 :1121 data1 :<div>dddddd</div> data2 :[object Object] data3 :function () { } data4 : data5 : data6 :1,2,3 data7 : -->
複製代碼
先來看一個列子json
//html:<input type="text" value="a">
var outPutVal = function(){
console.log('getAttribute:',inO.getAttribute('value'));
console.log('inO.value:',inO.value);
}
window.onload = function(){
var inO = document.querySelect('input');
outPutVal(inO);
//getAttribute: a
//inO.value: a
document.onclick = function(){
//<input type="text" value="a"> 手動輸入value爲aaaaa後打印
outPutVal(inO);
//getAttribute: a
//inO.value: aaaaa
}
}
複製代碼
以上原生js展現了HTML attribute 與 DOM property 的區別:緩存
angular中模板綁定是經過 property 和事件來工做的,而不是 attributebash
特殊的attribute 綁定app
[attr.aria-label]="actionName"
<td [attr.colspan]="1 + 1">
複製代碼
指令分爲三種:less
<div *ngIf="hero" class="name">{{hero.name}}</div>
-----------------------------------
<ng-template [ngIf]="hero">
<div class="name">{{hero.name}}</div>
</ng-template>
複製代碼
<div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd">
({{i}}) {{hero.name}}
</div>
-----------------------------------
<ng-template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
<div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</ng-template>
複製代碼
在渲染視圖以前,Angular 會把 < ng-template > 及其包裹內容替換爲一個註釋
會將兄弟元素歸爲一組而且ng-template 會無反作用的包裹內部元素
無反作用是什麼意思?(舉個例子:破壞了html結構!):
<p>
I turned the corner
<span *ngIf="hero">
and saw {{hero.name}}. I waved
</span>
and continued on my way.
</p>
---------------------------
<p>
I turned the corner
<ng-container *ngIf="hero">
and saw {{hero.name}}. I waved
</ng-container>
and continued on my way.
</p>
複製代碼
ng g c components/A 建立組件
複製代碼
//a.component.ts
@Input()
inAttr:String;
private _name:String = '';
----------------------------------------------------
@Input()
set inAttr2(name:String){
this._name = name;
}
get inAttr2():String{
return this._name;
}
複製代碼
//子組件中
@Output()
myEvent:EventEmitter<DataType> = new EventEmitter();
this.myEvent.emit(Data);
//父組件中
(myEvent)="myHandleEvent($event)"
myHandleEvent(Data:DataType){
}
複製代碼
@ViewChild(ChildComponent)
private childComponent: ChildComponent;
ngAfterViewInit() {
setTimeout(() => this.seconds = () => this.childComponent.changeData, 0);
}
複製代碼
ng g d myDirective/demo
複製代碼
ElementRef:對視圖中某個原生元素的包裝器。
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appDemo]'
})
export class DemoDirective {
//構造函數要聲明須要注入的元素 el: ElementRef。
constructor(private el:ElementRef) { }
// 註冊事件
@HostListener('click')
show(){
console.log(this.el.nativeElement);
console.log(this.ss);
}
//指令參數,當參數名與指令名相同時,能夠直接賦值給指令
@Input()
ss:String = 'aaa';
}
複製代碼
<button appDemo [ss]="bbb">click me</button>
複製代碼
TemplateRef:取得 < ng-template > 的內容
ViewContainerRef: 訪問視圖容器
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[appUnless]'})
export class UnlessDirective {
//第一次傳入true時不執行任何if分支,提高性能
private hasView = false;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set appUnless(condition: boolean) {
if (!condition && !this.hasView) {
//實列化一個試圖,並把它插入到該容器中
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (condition && this.hasView) {
this.viewContainer.clear();
this.hasView = false;
}
}
}
複製代碼
你能夠將管道理解成將數據處理以後再顯示的一種操做符,如:
<p>{{ birthday}}</p>
<p>{{ birthday | date }}</p>
<!--鏈式調用管道-->
<p>{{ birthday | date | uppercase}}</p>
複製代碼
DatePipe、UpperCasePipe、LowerCasePipe、CurrencyPipe 和 PercentPipe.......
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent: string): number {
let exp = parseFloat(exponent);
return Math.pow(value, isNaN(exp) ? 1 : exp);
}
}
複製代碼
Angular 只有在它檢測到輸入值發生了純變動時纔會執行純管道。 純變動是指對原始類型值(String、Number、Boolean、Symbol)的更改, 或者對對象引用(Date、Array、Function、Object)的更改。
Angular 會在每一個組件的變動檢測週期中執行非純管道。 非純管道可能會被調用不少次,和每一個按鍵或每次鼠標移動同樣頻繁。
@Pipe({
name: 'flyingHeroesImpure',
pure: false
})
export class FlyingHeroesImpurePipe extends FlyingHeroesPipe {}
複製代碼
依賴注入是實現控制反轉的一種方式,將對象的創造權交出去,它的好處能夠在實際開發中體現出來,如下會介紹它
依賴注入會讓你用一種鬆耦合的方式去寫代碼,易於調試:
舉個例子:
當你的服務分爲開發版本與線上版本時,你可能須要兩個不一樣的服務devDataSevice與proDataSevice, 當你不使用依賴注入時,你須要在多個組件中new 出這兩個對象來使用這兩個服務,在線上環境與測試環境之間切換時,你須要更改多個組件中的代碼,若是使用依賴注入的形式,你只須要更改提供器中的代碼就能夠更改全部組件中的服務,這大大下降了代碼的耦合程度而且提升了可維護性。
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class HeroService {
constructor() { }
}
複製代碼
在哪裏書寫服務提供商:
在服務自己的 @Injectable() 裝飾器中的 providedIn 的元數據選項
providedIn的值能夠是'root'或者某個特定的NgModule
在 NgModule 的 @NgModule() 裝飾器中的providers元數據選項
在組件的 @Component() 裝飾器中providers元數據選項
在指令的 @Directive() 裝飾器中providers元數據選項(元素級注入器)
providers中如何書寫:
provider:[ProductService]
provider:[{provide:ProductService,useClass:ProductService}]
provider:[{provide:ProductService,useClass:AnotherProductService}]
provider:[{provide:ProductService,useFactory:(參數A)=>{return ob},deps:[參數A]}]
provider:[{provide:"IS_DEV_ENV",useValue:{isDev:true}}]
複製代碼
在構造函數中注入:
construct(private productService:ProductService){...};
複製代碼
<!--index.html中的head標籤中加入<base href="/">來告訴路由該如何合成導航用的 URL-->
<base href="/">
複製代碼
//app.module.ts
//導入路由核心模塊
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{path:'**',component:AComponent}
];
@NgModule({
...
imports: [RouterModule.forRoot(routes)]
...
})
export class AppModule { }
複製代碼
path "**"表示匹配全部
redirectTo "表示要轉走的路徑"
pathMatch "full"表示匹配程度
component 表示要顯示的組件
data 數據傳遞
children:[] 子路由
canActivate:[PermissionGuard]
canDeactivate:[FocusGuard]
resolve:{Stock:StockResolve}
outlet 輔助路由
設置導航輸出位置
<router-outlet></router-outlet> <!-- Routed components go here --> 複製代碼
<a [routerLink]="['/path']" routerLinkActive="active">routelink</a>
<a [routerLink]="['./path']">routelink</a>
<a [routerLink]="['{outlets:{aux:'aaa'}}']">routelink</a> 輔助路由
http://localhost:4200/a(aux:aaa)
複製代碼
Router可調用navigate與navigateByUrl()
//1.
[routerLink] = "['/path',1]"
//http://localhost:4200/path/1
// this.routeInfo.snapshot.queryParams
//2.
[routerLink]="['/b',1]" [queryParams]="{id:3}"
// http://localhost:4200/b/1?id=3
// this.routeInfo.snapshot.params
// 3.
{path:'a',component:AComponent,data:{id:666}}
//this.routeInfo.snapshot.queryParams
//this.routeInfo.snapshot.data
複製代碼
export class PermissionGuard implements CanActivate{
canActivate(){
let hasPemission:boolean = Math.random() < 0.5;
return hasPemission;
}
}
複製代碼
export class FocusGuard implements CanDeactivate<CComponent>{
canDeactivate(component:CComponent){
if(component.isFoucs){
return true;
}else {
return confirm('不關注一下嘛?');
}
}
}
複製代碼
@Injectable()
export class StockResolve implements Resolve<Stock>{
constructor(
private route:Router
){}
resolve(route:ActivatedRouteSnapshot,state:RouterStateSnapshot){
return new Stock(1,'name');
}
}
複製代碼
當 Angular的 組件或指令, 新建、更新和銷燬時所觸發的鉤子函數
//1.constructor
//2.ngOnChanges
//3.ngOnInit
//4.ngDoCheck
//5.ngAfterContentInit
//6.ngAfterContentChecked
//7.ngAfterViewInit
//8.ngAfterViewChecked
複製代碼
//1.ngOnChanges
//2.ngDoCheck
//3.ngAfterContentChecked
//4.ngAfterViewChecked
複製代碼
//1.ngOnDestroy
// 在路由變動時改變
複製代碼
1.子組件
<div>
<ng-content></ng-content>
</div>
2.父組件
<SComponent>
<!--在此寫入的東西會投影到子組件-->
</SComponent>
複製代碼
<form #myForm="ngForm" action="/regist" (ngSubmit)="createUser(myForm.value)" method="post">
<div>
<input ngModel name="a" type="text" required pattern="[a-zA-Z0-9]+">
</div>
<div>
second:<input ngModel #second="ngModel" name="a" type="text" required pattern="[a-zA-Z0-9]+">
</div>
<div>
<input ngModel name="b" type="text" required pattern="[a-zA-Z0-9]+">
</div>
<div ngModelGroup="tow">
<input ngModel name="a" type="text">
<input ngModel name="b" type="text">
</div>
<button type="submit">提交</button>
</form>
<div>
{{myForm.value | json}}
<br>
second值是:{{second.value}}
</div>
複製代碼
private nickName = new FormControl('tom');
private passwordInfo = new FormGroup({
password: new FormControl(),
passwordConfirm:new FormControl()
});
private email = new FormArray([
new FormControl('a@a.com'),
new FormControl('b@b.com')
]);
複製代碼
管理單體表單控件的值和有效性狀態
管理一組 AbstractControl 實例的值和有效性狀態
管理一組 AbstractControl 實例的值和有效性狀態
<form [formGroup]="formModel" action="/regist" (Submit)="createUser()" method="post">
<input formControlName="nikname">
<ul formArrayName="emails">
<li *ngFor="let email of formModel.get('emails').controls;let i = index;">
<input [formControlName]="i">
</li>
</ul>
<button >增長email.....</button>
<input formControlName="emails">
<div formGroupName="passwordInfo">
<input formControlName="password">
<input formControlName="passwordConfirm">
</div>
</form>
複製代碼
private formModel:FormGroup;
private fb:FormBuilder = new FormBuilder();
/*this.formModel = new FormGroup({ nikname:new FormControl(), emails:new FormArray([ new FormControl() ]), mobile:new FormControl(), passwordInfo:new FormGroup({ password:new FormControl(), passwordConfirm:new FormControl() }) });*/
this.formModel = this.fb.group({
nikname:[''],
emails:this.fb.array([
['']
]),
mobile:[''],
passwordInfo:this.fb.group({
password:[''],
passwordConfirm:['']
})
});
複製代碼
//自定義校驗器
xxx(param:AbstractControl):{[key:string]:any}{
return null;
}
// eg:
moblieValid(moblie:FormControl):any{
..........
// return null;表示成功
// return {...};不成功
}
//預約義校驗器
Validators.required ......
nikname:["xxxx",[Validators.required,.....]]
.....................
let niknameValid;boolean = this.formModel.get('nikname').valid;
passwordInfo:this.fb.group({
password:[''],
passwordConfirm:['']
},{validator:this.passwordValidator}) //一次校驗多個字段
複製代碼
<div [hidden]="!formModel.hasError('required','nickname')"></div>
複製代碼