Angular基础
一、环境安装
1、全局安装
npm i -g @angular/cli
2、查看是否安装成功
ng v
3、创建项目
ng new ngdome(项目名称)
- --skip-install:跳过安装依赖
4、运行项目
ng serve --open
// 或者
npm start
5、app.module.ts文件介绍
定义了名为 AppModule
的根模块,告诉 Angular 如何组装应用。
// 核心模块
import { NgModule } from '@angular/core';
// 浏览器解析模块
import { BrowserModule } from '@angular/platform-browser';
// Form模块,按需引入
// import {FormsModule}from "@angular/forms"
// 路由模块,按需引入
// import { AppRoutingModule } from './app-routing.module';
// 根组件
import { AppComponent } from './app.component';
// 装饰器,告诉Angular如何编译和启动应用
@NgModule({
declarations: [ // 配置组件,引入自定义组件
AppComponent
],
imports: [ // 配置依赖的其他模块,如FormsModule、AppRoutingModule模块
BrowserModule,
// AppRoutingModule,
// FormsModule
],
providers: [], // 配置服务
bootstrap: [AppComponent] // 指定应用的根组件
})
export class AppModule { }
6、创建组件
ng generate component components/index(自己创建的文件夹及组件名)
// 简写
ng g c components/index(自己创建的文件夹及组件名字)
- 创建后会自动在
app.module.ts
文件引入
7、创建服务
7.1、创建服务
ng generate service services/storage
// 简写
ng g s services/storage
7.2、创建后需要在app.module.ts中引入
import {StorageService} from './services/storage.service'
@NgModule({
declarations: [ // 配置组件
AppComponent
],
imports: [ // 配置依赖的其他模块
BrowserModule
],
providers: [StorageService], // *此处引入自定义的服务
bootstrap: [AppComponent] // 指定应用的根组件
})
7.3、其他组件中使用时需要再次引入,然后初始化后使用
// 引入
import {StorageService} from '../../services/storage.service'
// 构造函数注入
constructor(public storage:StorageService) {
}
// 使用
btnclick(){
this.storage.setLocal('userName','张三')
}
二、语法
1、页面渲染
关键字:{{}}
{{要渲染的值}}
2、动态属性
关键字:[]
2.1、普通属性
<img [src]="imgurl" [alt]="提示" />
<a [href]="url">百度一下</a>
// 属性值拼接
<div [id]="'pre'+id">有id的div</div>
2.2、解析HTML
// 解析HTML
<div [innerHtml]="html"></div>
2.3、动态样式
// 动态Class
<div [ngClass]="{'orange':flag,'red':!flag}">动态样式</div>
// 动态style
<div [ngStyle]="{'background-color': style}">动态style</div>
3、循环
关键字:*ngFor
<li *ngFor="let item of items let i =index">{{item}}的索引是{{i}}</li>
4、条件判断
4.1、if
关键字:*ngIf
<div *ngIf="flag">条件判断</div>
<div *ngIf="!flag">条件判断否则</div>
4.2、switch
关键字:[ngSwitch]、*ngSwitchCase
<div [ngSwitch]="switch">
<div *ngSwitchCase="1">output 1</div>
<div *ngSwitchCase="2">output 2</div>
<div *ngSwitchCase="3">output 3</div>
<div *ngSwitchDefault>output default</div>
</div>
5、事件
关键字:()
5.1、点击事件
<button (click)="btnclick()">点击</button>
btnclick(){
alert('点击事件');
}
5.2、键盘事件
<input (keydown)="iptkeydown($event)" />
iptkeydown(e){
console.log(e.key);
console.log(e.keyCode);
}
- $event:事件对象
- keyCode:等于13时是回车事件
6、双向数据绑定
语法:[(ngModel)="变量名"]
<input type="text" [(ngModel)]="iptval" />{{iptval}}
- iptval:变量名
6.1、使用双向数据绑定必须在app.module.ts中引入表单模块
// app.module.ts
import {FormsModule}from "@angular/forms"
@NgModule({
declarations: [ // 配置组件
AppComponent,
],
imports: [ // 配置依赖的其他模块
BrowserModule,
AppRoutingModule,
FormsModule // 表单模块
],
providers: [], // 配置服务
bootstrap: [AppComponent] // 指定应用的根组件
})
export class AppModule { }
7、管道
关键字:|
<div>{{time | date:'yyyy-MM-dd HH:mm:ss'}}</div>
// 链式调用
<div>{{time | date:'fullDate' | uppercase}}</div>
三、组件间传值
1、父子间通过Input向子组件传值
1.1、子组件引入Input
import { Component, OnInit, Input } from '@angular/core';
1.2、定义要接收的父组件的值
// 接收数字类型的名叫psid的参数
@Input() psid: number = 0
// 接收字符串类型的名叫psmsg的参数
@Input() psmsg:string = ''
// 接收名叫psrun的方法
@Input() psrun:any
- 注意多个值时需要使用多个@Input()
- 子组件中可以直接使用this.xxx使用@Input定义的值,方法使用this.xxx()
1.3、父组件调用子组件时绑定属性值
<app-index-test [psid]="parentPsId" [psmsg]="'张三'" [psrun]="parentRun"></app-index-test>
- 传递的parentPsId参数和parentRun方法需要在父组件中定义好
2、父组件通过ViewChild获取子组件的数据和方法
2.1、父组件引入ViewChild
import { Component, OnInit, ViewChild } from '@angular/core';
2.2、给子组件设置名称
<app-index-test #indextest [psid]="parentPsId" [psmsg]="'张三'" [psrun]="parentRun"></app-index-test>
2.3、父组件获取子组件
@ViewChild('indextest') indextest:any
2.4、父组件使用子组件数据和方法
getChildTitle(){
alert(this.indextest.title)
this.indextest.execParent()
}
3、子组件通过@Output触发父组件方法
3.1、子组件引入Output和EventEmitter
import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
3.2、子组件实例化EventEmitter
@Output() private outer = new EventEmitter<string>()
3.3、子组件定义调用方法
<button (click)="sendParent()">子组件调用父组件</button>
sendParent(){
this.outer.emit("子组件调用父组件")
}
3.4、父组件调用子组件时定义接收方法
<app-index-test (outer)="childToParentRun($event)"></app-index-test>
3.5、父组件定义方法,子组件emit后该方法会自动执行
childToParentRun(e:string){
alert(e)
}
- e:为子组件传来的值
四、使用HttpClient远程请求
1、在app.module.ts中引入HttpClientModule
import { HttpClientModule } from '@angular/common/http'
@NgModule > imports数组中加入HttpClientModule
2、组件中引入HttpClient
import {HttpClient,HttpHeaders} from '@angular/common/http'
- HttpHeaders:需要设置请求头时引用
3、注入
constructor(public httpClient:HttpClient) {
}
4、使用
var options = {headers:new HttpHeaders({'Content-type':'application/json'})}
var data = {id:1}
this.httpClient.get("url",options).subscribe(res=>{})
this.httpClient.post("url",data,options).subscribe(res=>{})
this.httpClient.put("url",data,options).subscribe(res=>{})
this.httpClient.delete("url",options).subscribe(res=>{})
- 还有一些其他的API,使用时可具体查看
五、生命周期钩子
钩子方法 | 用途 | 时机 |
---|---|---|
ngOnChanges() |
当 Angular 设置或重新设置数据绑定的输入属性时响应。 该方法接受当前和上一属性值的 SimpleChanges 对象注意,这发生的非常频繁,所以你在这里执行的任何操作都会显著影响性能。 |
如果组件绑定过输入属性,那么在 ngOnInit() 之前以及所绑定的一个或多个输入属性的值发生变化时都会调用。注意,如果你的组件没有输入属性,或者你使用它时没有提供任何输入属性,那么框架就不会调用 ngOnChanges() 。 |
ngOnInit() |
在 Angular 第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。 | 在第一轮 ngOnChanges() 完成之后调用,只调用一次。而且即使没有调用过 ngOnChanges() ,也仍然会调用 ngOnInit() (比如当模板中没有绑定任何输入属性时)。 |
ngDoCheck() |
检测,并在发生 Angular 无法或不愿意自己检测的变化时作出反应。 | 紧跟在每次执行变更检测时的 ngOnChanges() 和 首次执行变更检测时的 ngOnInit() 后调用。 |
ngAfterContentInit() |
当 Angular 把外部内容投影进组件视图或指令所在的视图之后调用。 | 第一次 ngDoCheck() 之后调用,只调用一次。 |
ngAfterContentChecked() |
每当 Angular 检查完被投影到组件或指令中的内容之后调用 | ngAfterContentInit() 和每次 ngDoCheck() 之后调用 |
ngAfterViewInit() |
当 Angular 初始化完组件视图及其子视图或包含该指令的视图之后调用。 | 第一次 ngAfterContentChecked() 之后调用,只调用一次。 |
ngAfterViewChecked() |
每当 Angular 做完组件视图和子视图或包含该指令的视图的变更检测之后调用。 | ngAfterViewInit() 和每次 ngAfterContentChecked() 之后调用。 |
ngOnDestroy() |
每当 Angular 每次销毁指令/组件之前调用并清扫。 在这儿反订阅可观察对象和分离事件处理器,以防内存泄漏。 | 在 Angular 销毁指令或组件之前立即调用 |
本文作者:gaozejie
版权声明:本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。