Angular 使用手册

972 阅读7分钟

1.首先我们要npm 安装angular-cli npm i -g @angular/cli

创建一个自己的项目

ng new myAn

myAn是我们的项目名。

angular组件结构

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'myAn';
}

组件生成

从angular主模块中获取组件装饰器

import { Component } from '@angular/core';

调用组件装饰器定义,以json方式传入组件源数据 @Component(json)

selectore:string  组件标签名 <string></string>调用

temlateUrl:string   组件html模板路径

styleUrls:Array<string>   组件css文件路径数组

定义组件控制器,逻辑代码的地方

export class AppComponent{}

模块组成器

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

引入模块生成器 @NgModule

import { NgModule } from '@angular/core';

模块生成器的参数json

declarations: Array   组合模块的组件和管道的数据源

imports:modules  模块依赖项

providers:Array  模块提供的服务

bootstrap:Array  模块的主组件

创建组件命令

ng g component 组件名

外部传入值属性

需要import @Input 核心模块

import {Input} from "@angular/core"

export class Componet {
    //声明可外部传值变量
    @Input
    props:[];
    //声明完毕
}

外部对组件标签传值

<Componet [props]="[0,1,3]"></Componet>

循环指令

*ngFor="let a in Array;let i in index "

a: 代理条目

index: 索引

属性绑定指令 []

绑定class

[class.newClass]=bloore  或  [ngClass]={'a':true,'bb':false,'c':true}

绑定style

[style.font-size]='24px'  或  [ngStyle]={ 'font-size':'24px' , 'color': a>10 ?'red':'#fff' }


Angular路由系统

路由对象

Routes:Array<json> 路由配置项

<router-outlet></router-outlet> 路由视图view标签

Router 路由器对象,可以通过调用其navigate()和navigateByUrl()方法来导航到一个指定的路由

Router.navigate(Array<string>)  将路由跳转到指定路由['/']

routerLink:string  将标签为路由导航的属性<a router-link="home"></a>

ActivatedRouter  当前路由激活的对象。当前路由地址,路由参数

路由配置项参数 routes

Routes:Array<json>

json: {path: '',component : center}

path: 路由路径,不带/,通配符 **

component:object 组件对象

当前路由激活对象属性和方法 ActivatedRouter 

proto.queryParams[id] 当前路由激活对象的get参数对象= ?id=10

proto.params[id]  当前路由激活对象的参数= a/:id

proto.data[index].id 当前路由激活的data数据 =  [path:'',component:com,data:[{id:abc}]]

重定向路由 redirectTo 和 pathMatch

{path:'', redirectTo:'/home',pathMatch:'full'}

redirectTo:string重定向到的路由地址

pathMatch:full 是否开启精确模式

辅助路由

html占位符结构:

//路由输出器
<router-outlet></router-outlet>
//辅助路由输出器"aux"
<router-outlet></router-oulet name='aux'>

路由配置:

routes=[
    {path:'',component:center},//主路由显示器显示
    {path:'auxVivwe',component:auxViwe,outlet:'aux'}//辅助路由显示
    {path:'abcd',component:abcd,outlet:'aux'}//辅助路由显示

]

路由导航:

主路由为/,辅助路由跳转到auxVivwe
<a [routerLink]="['/',{outlet:'aux','auxVivwe'}]">1</a>

路由守卫

CanActivate:fun处理路由到某路由的情况调用,方法返回真允许路由进入,返回假阻止路由。

CanDeactivate:fun 处理当前路由离开的状况调用,

Resolve:fun 在路由激活数据之前调用

对路由注入路由守卫

{path:'/home',component:a,CanActivate:[abc实例,]}

路由数据获取函数

object.subscribe(backFuntion)  订阅数据,对象数据发生改变立即调用回调方法

object.snapshot.object  获取数据快照

依赖注入,控制反转

注入器:

constructor(prod:prod){}

提供器:

providers:[{provider:'prod',useClass:prod}]  直接实例

providers:[{provider:'prod',useFactory:()=>{ return 1},deps:[loge]}]   提供工厂方法值

providers:[{provider:'prod',useValue:false}]   提供一个值

配置参数

provider:string 签名

useClass:class 提供的实例

useFactory:function   通过方法返回类或值,工厂方法只会在需要提供服务时候被调用一次所返回的值会常驻并且后续的使用直接返回此值

deps:Array<class>  为工厂方法提供的中间提供器,它所提供的服务其他是从@ngModule或@component中查找过来的

提供器 providers 可以在@ngModuls()或@component中声明

数据绑定

1.插值表达式绑定  <h1>{{init}}~</h1>

2.将变量值或表达式单向绑定到DOM属性上  <img [src]="ImgData">

3.将变量值或表达式单向绑定到HTML属性上 <img [attr.src]='imgData' 

4.事件绑定,使用括号绑定事件 <div (click)="loader()"></div>

5.class绑定(全class替换成指定) <div class="aa bb" [class]="className"></div>//.className

6.class绑定 (增加或取消此class) <div class='aa bb' [class.cc]="true"></div>//.aa .bb .cc

7.class绑定,json表达式  <div [ngClass]="{aa:false,bb:true}">//.bb

8.style样式绑定,指定样式表达式 <div [style.color]="a?red:green">

9.style样式绑定,josn表达式  

<div [ngStyle]={'font-0size':a?'12px':'30px','color':a?'red':'green'}>

10.双向绑定 ,控制器值与视图值同步更新 <input [(ngModel)]="name">

管道(过滤器)

将值进行过滤后返回

与VUE中写法一样  {{value| fun }}

angular内置管道

转换成时间data格式  date:'yyyy-mm-dd'

转换成全部大写  uppercase

转换成小写  lowercase

转换数字格式 number:'2.2-2'

自定义管道需要声明在declarations中初始化

创建自定义管道  命令行 ng g pipe /piper/modele/  


组件之间通信

父子组件通信

父传值

@Input()
a:string;
<app-e  [a]='hello'></app-e>

子发射事件属性,父组件接收事件触发 : EvnetEmitter

//父组件模板
<div>
    <app-son (close)="setClose()"> </app-son>
</div>

exprot class app{
    setClose(){
        console.log('子组件要关闭拉')
    }
}

//子组件
<input type="button" (click)="postClose">

exprot class son{
    //发射事件属性声明
    @Output('close')
    emit:EventEmitter<any>=new EventEmitter()

    postClose(){
        //发射
        this.emit.emit()
    }
}

@Output('close')
emit:EventEmitter<any>=new EventEmitter()

表示发射出去的事件名为close。

EventEmitter 是angalur的事件触发对象

父组件调用子组件的方法 @ViewChild();

@ViewChild('child')
child1:component

this.child1.get();//调用子组件的方法


组件生命周期钩子

钩子

用途及时机

ngOnChanges()

当 Angular(重新)设置数据绑定输入属性时响应。 该方法接受当前和上一属性值的 SimpleChanges 对象

当被绑定的输入属性的值发生变化时调用,首次调用一定会发生在 ngOnInit() 之前。

ngOnInit()

在 Angular 第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。

在第一轮 ngOnChanges() 完成之后调用,只调用一次

ngDoCheck()

检测,并在发生 Angular 无法或不愿意自己检测的变化时作出反应。

在每个 Angular 变更检测周期中调用,ngOnChanges()ngOnInit() 之后。

ngAfterContentInit()

当把内容投影进组件之后调用。

第一次 ngDoCheck() 之后调用,只调用一次。

ngAfterContentChecked()

每次完成被投影组件内容的变更检测之后调用。

ngAfterContentInit() 和每次 ngDoCheck() 之后调用

ngAfterViewInit()

初始化完组件视图及其子视图之后调用。

第一次 ngAfterContentChecked() 之后调用,只调用一次。

ngAfterViewChecked()

每次做完组件视图和子视图的变更检测之后调用。

ngAfterViewInit() 和每次 ngAfterContentChecked() 之后调用。

ngOnDestroy()

当 Angular 每次销毁指令/组件之前调用并清扫。 在这儿反订阅可观察对象和分离事件处理器,以防内存泄漏。

在 Angular 销毁指令/组件之前调用。

自定义投影内容到组件中 ng-centent

//组件1模板内容
<div>
    <ng-centent></ng-centent>
</div>

//组件2调用传入投影
<app-component1>
    <h1>123456,我是投影进来的</h1>
</app-component1>

angalur表单处理 ngFrom

在angalur中会自动为from表单添加ngFrom指令进行所有表单数据被绑定ngModule的指令进行自动处理

ngFrom 当表单被添加ngFrom指令时候可以通过myFrom访问所有表单数据

ngSubmit anglular中使用ngSubmit事件代替原生的submit提交事件

ngModuleGroup  表单数据对象的子集。

响应式表单 reactiveFromsModule