angular知识点整理
创建项目
安装Angular-cli
npm install -g @angular/cli
创建项目 --skip-install忽视安装包
ng new angularApp --skip-install
安装模块
cnpm install
启动开发服务命令
Npm start
Ng serve --open //自动打开浏览器
启动时候打开浏览器
ng serve --open
创建组件命令
ng g component components/news
组件使用:
<app-news></app-news>
基础语法
Angular插值
语法:{
{ …变量和表达式}}
应用:应用于html内容里,也可以应用于property里
<h1 [innerHtml]="htmlStr"></h1>
Angular 绑定class
定义的class三种方式,跟VUE一致,会自动的将变量和原有的HTML的CLASS相加
<!-- 定义变量的方式 -->
<h1 class="abc" class="{
{classStr}}">class1</h1>
<h1 class="abc" [class]="classStr">class2</h1>
<h1 [attr.class]="classStr">class3</h1>
Class变量类型
<!-- 变量类型 -->
<!-- 字符串模式 -->
<h1 [class]="classStr">class4</h1>
<h1 class="a" [class]="'str abc'">class4</h1>
<!-- 对象模式 -->
<h1 [class]="classObj">class5</h1>
<h1 [class]="{bgBlue:isShow}">class6</h1>
<!-- 数组模式 -->
<h1 [class]="['bgBlue','active','abc']">class7</h1>
<h1 [class]="classArr"></h1>
Angular 绑定style
<!-- style -->
<!-- style表达式类型 -->
<!-- 字符串变量 -->
<h1 [style]="styleStr"></h1>
<!-- 对象模式 -->
<h1 [style]="styleObj"></h1>
<!-- 橙色 -->
<h1 [style.height]="styleObj.width">h</h1>
<h1 [style.width]="colorAbc"></h1>
<h1 [style.width.px]="widthNum"></h1>
Angular 绑定事件
<!--
绑定事件:
由等号左侧写小括号加上事件名称,右边写调用的事件函数
-->
<button (click)="changeColor()">改变颜色</button>
<button (click)="changeButton($event)">改变颜色</button>
Angular 条件渲染
<!-- 条件渲染 -->
<!-- person如果是广东人,就显示广东人的疫情信息 -->
<div *ngIf="person=='广东人'">
广东:1000人
</div>
<div *ngIf="person=='湖北人'">
湖北:40000人
</div>
<button (click)="togglePerson()">切换身份</button>
<h1>style的条件渲染</h1>
<!--
这里使用的条件渲染,会移除出Document,添加进DOM都会消耗性能。
-->
<!-- 使用STYLE进行条件渲染,如果需要频繁切换内容,那么需要style完成条件渲染-->
<div [style.display]="person=='广东人'?'block':'none'">
广东:1000人
</div>
<div [style.display]="person=='湖北人'?'block':'none'">
湖北:40000人
</div>
<!-- 条件渲染,匹配多种情况 -->
<div [ngSwitch]="homeState">
<div *ngSwitchCase="'睡觉'">卧室</div>
<div *ngSwitchCase="'看电视'">客厅</div>
<div *ngSwitchCase="'吃饭'">餐厅</div>
<div *ngSwitchCase="'发呆'">阳台</div>
<div *ngSwitchDefault>厕所</div>
</div>
<!-- 条件渲染,匹配多种情况 -->
<div [ngSwitch]="orderState">
<div *ngSwitchCase="1">待付款</div>
<div *ngSwitchCase="2">已付款</div>
<div *ngSwitchCase="3">发货</div>
<div *ngSwitchCase="4">已收货</div>
<div *ngSwitchDefault>丢失</div>
</div>
Angular 循环渲染
<!-- 列表循环 -->
<ul>
<li *ngFor="let item of arr">{
{
item}}</li>
</ul>
<!-- 列表循环获取索引值 -->
<ul>
<li *ngFor="let item of arr;let i=index">索引值:{
{
i}};内容:{
{
item}}</li>
</ul>
<!-- 将列表的内容传入事件 -->
<ul>
<li *ngFor="let item of arr;let i=index" (click)="choosePerson(item,i)">索引值:{
{
i}};内容:{
{
item}}</li>
</ul>
<!-- 循环复杂数组 -->
<ul>
<li *ngFor="let item of students;let key=index">{
{
key}}-{
{
item.name}}的爱好是{
{
item.hobby}}</li>
</ul>
双向数据绑定
基础语法
导入FormsModule模块至app.module.ts
import {
BrowserModule } from '@angular/platform-browser';
import {
NgModule } from '@angular/core';
//导入form模块
import {
FormsModule} from '@angular/forms'
import {
AppComponent } from './app.component';
import {
NewsComponent } from './views/news/news.component';
@NgModule({
declarations: [
AppComponent,
NewsComponent
],
imports: [
BrowserModule,
//导入form模块
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
表单的数据绑定
<input type="text" [(ngModel)]="username">
设置临时变量绑定DOM对象
<!-- 表单数据获取 -->
<div>
<label for="">用户名</label>
<input #input1 type="text" >
</div>
<div>
<label for="">密码</label>
<input #input2 type="text" >
</div>
<button (click)="getContent(input1.value,input2.value)">获取账号密码</button>
NgForm获取整个表单的数据
导入ReactiveFormsModule模块至app.module.ts:
import {
NgModule } from '@angular/core';
import {
BrowserModule } from '@angular/platform-browser';
//导入form模块
import {
FormsModule ,ReactiveFormsModule} from '@angular/forms'
import {
AppComponent } from './app.component';
import {
NewsComponent } from './components/news/news.component';
@NgModule({
declarations: [
AppComponent,
NewsComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
使用:
<form #myForm="ngForm">
<input type="text" [(ngModel)]="usernamer" name="username" >
<input type="text" [(ngModel)]="password" name="password" >
<button (click)='eventFn(myForm.value)'>按钮</button>
</form>
管道(处理数据)
基础语法
<h1>{
{
student | json}}</h1>
<h1>显示时间:{
{
time | date:"yy/MM/dd"}}</h1>
<h1>用户名: {
{
username | uppercase}} </h1>
//管道可以转换多次
<h1>{
{
'abcdefg'|uppercase|lowercase}}</h1>
常用值:
1、大小写转换管道
uppercase将字符串转换为大写
lowercase将字符串转换为小写
<p>{
{
str | uppercase}}-{
{
str1 | lowercase}} </p> //str:hello str1:WORLD
页面上显示:HELLO-world
2、日期管道
date:日期管道符可以接受参数,用来规定输出日期的格式。
<p>现在的时间是{
{
today | date:'yyyy-MM-dd HH:mm:ss'}}</p>
today = new Date();
页面上显示:现在的时间是2019-04-02 16:08:10
3、小数管道
number管道用来将数字处理为我们需要的小数格式
接收的参数格式为{最少整数位数}.{最少小数位数}-{最多小数位数}
其中最少整数位数默认为1
最少小数位数默认为0
最多小数位数默认为3
当小数位数少于规定的{最少小数位数}时,会自动补0
当小数位数多于规定的{最多小数位数}时,会四舍五入
<p>num保留4位小数的值是:{
{
num | number:'3.2-4'}}</p>
num = 125.156896;
页面上显示:num保留4位小数的值是:125.1569
4、货币管道
currency管道用来将数字转换为货币格式
<p>数量:{
{
count}}</p>
<p>价格:{
{
price}}</p>
<p>总价:{
{
(price * count) | currency:'¥'}}</p>
count = 5;
price = 1.5;
页面上显示:
数量:5
价格:1.5
总价:$7.50
5、字符串截取
slice:start[:end] //开始下标到结束下标 不包括结束下标
<p>{
{
name | slice : 2 : 4}}</p>
name = '只对你说';
页面上显示:你说
6、json(数据)格式化
<div>
<p>{
{
{
name: 'semlinker' } | json }}</p>
</div>
页面上显示:{
"name": "semlinker" }
自定义管道
创建自定义的管道文件
ng g pipe filter/lcUppercase
import {
Pipe, PipeTransform } from '@angular/core';
// @Pipe({
// name: 'lcUppercase'
// })
// export class LcUppercasePipe implements PipeTransform {
// transform(value:string,...args:string[]):string {
// if(value=="老陈"){
// return "大帅哥老陈"
// }
// return value ;
// }
// }
@Pipe({
name: 'lcUppercase'
})
export class LcUppercasePipe implements PipeTransform {
transform(value:string,...args:string[]):string {
console.log(args)
return '¥'+value+args[0];
}
}
模板
注意:msg是模板变量,lcUppercase是转换函数,:后面是参数
```javascript
<h1>{
{
msg|lcUppercase:'元'}}</h1>
父子之间传参
父组件传值给子组件
父组件设置
<app-child [item]="sendchildMsg"></app-child>
子组件设置 (需要在子组件引入 Input)
import {
Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() item;
constructor() {
}
ngOnInit(): void {
}
}
子组件Template
<h1>{
{
item}}</h1>
子组件传值给父组件
父组件Template
<app-child (childMsg)="getEvent($event)"></app-child>
父组件Ts
import {
Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
getChildMsg="";
getEvent(event){
console.log(event)
this.getChildMsg = event.msg
}
}
子组件设置(需要引入Output,EventEmitter)
import {
Component, OnInit,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
//实例化事件对象
@Output() childMsg=new EventEmitter()
constructor() {
}
ngOnInit(): void {
}
sendMsg(){
//发送消息
this.childMsg.emit({
msg:"我子组件,这是我发给父组件的消息"})
}
}
子组件Template
<button (click)="sendMsg()">发送消息给父组件</button>
父组件调用子组件的方法
父组件Template(需要在子组件的标签上添加 #child)
<app-news #child > </app-news>
<button type="button" (click)="getChildFun()">调用子组件方法按钮</button>
父组件Ts (需要引入ViewChild)
import {
Component,ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
//注册
@ViewChild('child')
child;
getChildFun(){
this.child.sendMsg()
}
}
子组件
import {
Component, OnInit,} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
constructor() {
}
ngOnInit(): void {
}
//子组件的方法
sendMsg(){
console.log("这是子组件的方法")
}
}
子组件调用父组件的方法(和子传父一样)
父组件Template
<h1>{
{
title}}</h1>
<app-news (parentFun)="parentFun()" > </app-news>
父组件Ts
import {
Component,ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = '父组件';
parentFun(){
console.log("这是父组件的方法")
}
}
子组件Template
<p>子组件</p>
<button type="button" (click)="getParentFun()">点击触发父组件的方法</button>
子组件Ts
import {
Component, OnInit,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
constructor() {
}
ngOnInit(): void {
}
@Output() parentFun=new EventEmitter()
getParentFun(){
this.parentFun.emit()
}
}
兄弟组件之间传参(就是父子组件的消息传递,父组件为桥梁)
父组件Template
<app-child1 #child1 (parentFun)="parentFun()"></app-child1>
<app-child2 #child2></app-child2>
父组件组件Ts
import {
Component,ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = '父组件';
@ViewChild('child2')
child2;
parentFun(){
this.child2.child2Fun()
}
}
child1Template
<p>child1 works!</p>
<button type="button" (click)="getParentFun()">点我调用Child2组件的方法</button>
child1组件Ts
import {
Component, OnInit ,Output,EventEmitter} from '@angular/core';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.scss']
})
export class Child1Component implements OnInit {
constructor() {
}
ngOnInit(): void {
}
@Output() parentFun=new EventEmitter()
getParentFun(){
this.parentFun.emit()
}
}
child2Template
<p>child2 works!</p>
child2组件Ts
import {
Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child2',
templateUrl: './child2.component.html',
styleUrls: ['./child2.component.scss']
})
export class Child2Component implements OnInit {
constructor() {
}
ngOnInit(): void {
}
child2Fun(){
console.log("这是child2组件中的方法")
}
}
生命周期
import {
Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angularapp';
constructor(){
console.log("组件构造函数调用")
}
//指令有效
ngOnChanges(){
//console.log("数据发生变化之时就会调用此函数ngOnChanges")
}
ngOnInit(){
console.log("第一次显示数据绑定和指令输入属性之后,就会调用,只调用一次")
}
ngDoCheck(){
console.log('在ngOnChanges和ngOnInit发生之后,会进行一次检测')
}
ngAfterContentInit(){
console.log('数据内容渲染到视图上之后')
}
ngAfterContentChecked(){
console.log('数据内容渲染到视图检测之后')
}
ngAfterViewInit(){
console.log('完成组件和子组件初始化')
}
ngAfterViewChecked(){
console.log('完成组件和子组件初始化检测后')
}
ngOnDestory(){
console.log("销毁组件")
}
}
自定义指令
创建指令文件:
ng g directive directive/lcstyle
设置指令内容和功能 lcstyle.ts
import {
Directive,Input,ElementRef } from '@angular/core';
@Directive({
selector: '[appLcstyle]'
})
export class LcstyleDirective {
@Input() appLcstyle;
constructor(public ref:ElementRef) {
console.log('constructor')
}
ngOnChanges(){
//console.log('指令')
//console.log("数据发生变化之时就会调用此函数ngOnChanges")
//console.log(this.appLcstyle)
//console.log(this.ref)
this.ref.nativeElement.className = this.appLcstyle;
this.ref.nativeElement.innerHTML = this.appLcstyle;
this.ref.nativeElement.addEventListener("click",()=>{
this.ref.nativeElement.style.background="pink"
})
}
}
使用
<h1 [appLcstyle]="'aaa'"></h1>
Axios的使用
第一步:安装axios
npm install axios
第二步:声明axios 在需要用到的地方
import axios from ‘axios’
第三步:使用方法
//Angular生命周期:初始化
ngOnInit(){
axios.get("路径").then(res=>{
console.log(res)
}).catch((err)=>{
console.log(err);
}).finally(()=>{
console.log('执行完了');
});
}
路由
基础语法
1、创建路由指令
生成的 app-routing.module.ts 和 app-routing.module.spec.ts 是与 app.module.ts 在同一目录下的,也就是都在app目录下
ng generate module app-routing --flat --module=app
路由配置app-routing.module.ts
import {
NgModule } from '@angular/core';
import {
Routes, RouterModule } from '@angular/router';
import {
IndexComponent} from './view/index/index.component';
import {
AboutComponent} from './view/about/about.component';
import {
NewsComponent} from './view/news/news.component'
//配置路由对象
const routes: Routes = [
{
//不需要加/
path:"",
component:IndexComponent
},
{
path:'about',
component:AboutComponent
},
{
path:"news",
component:NewsComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
HTML模板
<!-- 根据路径的变化,显示不同组件 -->
<style>
div>span{
margin: 20px;
padding: 5px 10px;
background-color: skyblue;
}
</style>
<div>
<span [routerLink]="['/']" routerLinkActive="router-link-active" >首页</span>
<span [routerLink]="['/about']" routerLinkActive="router-link-active" >about</span>
<span [routerLink]="['/news']" routerLinkActive="router-link-active" >news</span>
</div>
<router-outlet></router-outlet>
子路由
{
path:'admin',
component:AdminComponent,
children:[
{
path:'user',
component:UserComponent
},
{
path:'product',
component:ProductComponent
}
]
},
HTML模板设置
<p>admin works!</p>
<div class="admin">
<div class="left">
这是侧边栏
<div [routerLink]="['/admin/user']" routerLinkActive="router-link-active" >user</div>
<div [routerLink]="['/admin/product']" routerLinkActive="router-link-active" >product</div>
</div>
<div class="main">
<router-outlet></router-outlet>
</div>
</div>
路由传参
动态路由
{
//动态路由
path:"news/:id",
component:NewsComponent
},
获取动态路由的参数(需引入ActivatedRoute)
import {
Component, OnInit } from '@angular/core';
//导入route
import {
ActivatedRoute} from '@angular/router'
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
title = ""
//注入route
constructor(public route:ActivatedRoute) {
}
ngOnInit(): void {
//let params = this.route.params;
//console.log(params.value.id);
}
goParams(){
//使用参数
this.route.params.subscribe((params)=>{
console.log(params)
this.title = params.id;
})
}
}
编程式导航
1/依赖注入router
import {
Component, OnInit } from '@angular/core';
//导入route,router
import {
ActivatedRoute,Router} from '@angular/router'
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
//注入route,router
constructor(public route:ActivatedRoute,public router:Router) {
this.route.data.subscribe((data)=>{
console.log(data)
this.title = data.msg
})
}
ngOnInit(): void {
}
goParams(){
// 获取路由传参
this.route.params.subscribe((params)=>{
console.log(params)
this.title = params.id;
})
}
goHome(){
//第一个参数是传入数组(路径的数组),路由path名称,
// 第二个参数是路由的参数,需要在路由文件进行配置,比如{path:"admin/:id"},传的就是id
this.router.navigate([''],{
queryParams:{
usernam:"admin"
},
fragment:"abc",//传hash值
replaceUrl:true//是不是要替换当前的页面
})
}
}
打包
ng build