angular1

Angular基本概念

项目启动过程

Angular核心概念

  • Module: 模块,NG中的模块就是一个抽象的容器,用于对组件进行分组,整个应用初始时只有一个主模块 AppModule
  • 组件: Component 是一段可以反复使用的页面片段,任何一个组件都必须声明在一个模块中

自定义组件

    1. 创建组件class

    mycomponent.ts

import {Component} from '@angular/core'  //导入装饰器
//装饰器--用于指定class的用途 
//组件 = 模板+脚本(export)+样式 
@Component({
    template: 'html模板',
    templateUrl: '',
    styleUrls: '',
    selector: 'my-component' //当作元素用<my-component></my-component>
    selector: '.my-component' //当作类用 
    selector: '[my-component]' //当作属性用
})
export class MyComponent{
    //注册引用的模块名
}
    1. 在某个模块中注册组件class

    app.module.ts

import { MyComponent } from './mycomponent'
//表明此文件是模块
@NgModule({  //宣称、声明
    declarations:[MyComponent] //声明组件
    imports: []  //导入模块
})
export class AppModule{

}
    1. 使用注册过的组件

    app.component.html

    <my-component></my-component>

    属性绑定

    <p [title]:'msg'>  <!--使用[]做属性绑定-->
    <p title='{{msg}}'>   <!--直接在属性上用{{}}-->

    事件绑定

    <button (click)='printName()'>  <!--绑定事件-->

    Angular指令

    • 组件指令: NG中Component继承自Directive
    • 结构型指令: 会影响DOM树结构,必须以*开头
    • 属性型指令:不会影响DOM树结构,只影响元素外观或行为,必须用[]

    括起来

服务和依赖注入

  • Service: 组件是与用户交互的一种对象,其中的内容都应该与用户操作有关系,而与用户操作无关的内容都应该剥离出去,放在‘服务对象‘中,在外部为组件服务,如:日志记录、计时统计

创建对象的两种方式

  • 1.手工创建:let c2 = new Car()
  • 2.依赖注入式:无需new, 只需声明依赖,服务提供者就会创建被依赖的对象,注入给服务需要者

创建服务

import { Injectable } from '@angular/core';
@Injectable({
    providedIn: 'root' //指定当前服务对象在根模块中提供 appModule
})
export class LogService{
    //处理函数
    doLog(){
        //action
    }
}

组件中声明依赖,组件中直接使用即可

export class myComponent{
    log = null
    constructor(private log:LogService){
        this.log = log;
    }
doAdd(){
    this.log.doLog();
}
}

HttpClient Service

Angular官方提供的服务对象,用于向指定URL发起异步请求,使用步骤:

1. 在主模块中导入HttpClient服务所在模块

app.module.ts

imports: [HttpClientModule]

2. 在组建中声明依赖

http = null
constructor(private http:HttpClient){
    this.http =http
}
doAction(){
    let url = 'http://test.com'
    this.http.get(url).subscribe((res:any)=>{
        console.log(res); //得到响应
    })
}

组件的声明周期钩子函数

Angular 中的组件的声明周期钩子函数调用顺序:

    1. constructor() 组件对象被创建了
    2. ngOnChanges() 组件绑定的属性值发生改变
    3. ngOnInit() 组件初始化完毕
    4. ngDoCheck() 组件检查到了系统对自己的影响
    5. ngAfterContentInit() 组件的内容初始化完成
    6. ngAfterCotentChecked() 组件的内容发生变化需要检查
    7. ngAfterViewInit() 组件的视图初始化完成
    8. ngOnDestory() 组件即将从DOM树上卸载

   转载规则


《angular1》 由 fightingtree 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录