angular通信
父向子传
父组件:<A [test]="true"></A>
子组件接收:@Input() test
---
子组件->父组件
父组件接收:<A (test)="test1($event)"></A>
子组件:@Output test=new EventEmitter<any>(); close(){this.test.emit('parmas')}
---
兄弟组件A组件,B组件
A组件使用B组件
B组件[selector]='app-A'
A组件html直接用<app-A></app-A>
---
A组件使用B组件中的方法
A组件 import {A} from '../../file'
@viewChild(A) private testA
使用 this.testA.methodName
---
服务传值
A.services.ts
注入器@Injectable({'providedIn(提供器)':'root'})
A组件...
A组件(shard文件引入了所有的服务指令管道组件等) import { AServices} from '@shared'
构造函数引入进来 private testService:AServices
使用:this.testService.方法名...
---
跳转传值
A组件,B组件
A组件跳B组件1,引入路由,并在构造函数中申明(eg:route)
使用:this.route.navigate(['.../B组件'],{queryParams:obj(对象)})
B组件取值:import {ActivatedRoute} from '@angular/router'
构造函数导入 private actRouter: ActivatedRoute
this.actRouter.queryParams.subscribe(data=>{传过来的参数})
----使用过得通信方式END--------------
管道pipe
释:就是angular1中的过滤器
管道->主要用于数据转换,比如我们第一次拿到数据不能直接使用,手动2次处理会影响性能,就可以使用管道,管道是angular提供的一种特性,性能远好于2次手动处理的
内置管道:DatePipe、UpperCasePipe、LowerCasePipe、CurrencyPipe
语法:import {Pipe,PipeTransform} from '@angular/core'
@Pipe({name:'test_set'})
export..{
contructor(){}
transform(A:string,B:[],...args:unknow[]):unknow{
//比如写一个数组去重
return [...new Set(B)]
}
}
使用1:<p *ngFor="item in arr | test_set">{{item}}</p>
多个参数使用:<p *ngFor="item in arr | test_set:'1':'2'">{{item}}</p>
指令
自定义指令:directive.ts文件
语法:
import { Directive,HostListener } from '@angular/core'
import {NgControl} from '@angular/forms'
@Directive({selector:'[input-trim]'})
export class A{
constructor(private control:NgControl){}
@HostListener('keyup',['$event','$event.target])
keyupFun(e,tar){
if(tar.value){
this.control.control.setValue(tar.value.replaceAll(' ',''))
//this.control.control.setValue(tar.value.replaceAll(/\s*/g,''))
}
}
}
使用:<input nz-input input-trim>
使用2添加背景:
import { Directive,HostListener,Input,ElementRef } from '@angular/core'
@Directive({selector:'[appHighlight]'})
export HighlightDirective{
@Input('appHighlight') highColor:string;
constrouctor(private el:ElementRef){}
@HostListener('mouseenter') onMouseEnter(){
this.highColor(this.highColor)
}
@HostListener('mouseleave') onMouseLeave(){
this.highColor(null)
}
private highColor(color:string){
this.el.nativeElement.style.backgroundColor = color
}
}
使用带参数:<p *ngFor="let item in arr" appHighlight="#ccc">{{item}}</p>
服务
服务:主要用于实现一些公共方法等逻辑,比如文件导出,判断权限读写,以及一些其他的公共方法等可使用
import { Injectable } from '@angular/core';
@Injectable({providedIn:"root"})//注入到app.module中 供其他组件都可以导入使用
export class StorageService {
// 封装一个localStorage服务
constructor() { }
set(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value)); // 只能是字符串
}
get(key): any {
return JSON.parse(localStorage.getItem(key));
}
remove(key): void {
localStorage.removeItem(key);
}
}
使用:
doSubmit(): void {
this.storage.set('peopleInfo', this.peopleInfo); // 缓存的旧数据
}
getHistory(): void { // ****
// 从localStorage中取出数据
console.log('get')
this.peopleInfo = this.storage.get('peopleInfo');
}