1. ng g service servicename 创建一个服务,可以在多个组件里被调用,且数据保持,于是这个服务就可以用来进行一个特定方法的封装,比如socket,http又或者作为一个传递数据的BUS使用
// store.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StoreService {
constructor() { }
getData(){
console.log('一些操作');
}
}
// app.component.ts
import { StoreService } from './service/store.service'
constructor( private store:StoreService){
this.store.getData(); //直接调用
}
2.ng g directive directiveName 是创建一个指令,就像angular内置的*ngIf,*ngFor这样的指令一样,指令又分属性型和结构型
- 属性型,用于改变一个 DOM 元素的外观或行为
<p appDemoa="yellow">23333</p>
//demoa.directive.ts
import { Directive,ElementRef } from '@angular/core';
@Directive({
selector: '[appDemoa]'
})
export class DemoaDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
//高级扩展版本
import { Directive,ElementRef, HostListener,Input } from '@angular/core';
@Directive({
selector: '[appDemoa]'
})
export class DemoaDirective {
@Input('appDemoa') highlightColor: string;
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || 'red');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
- 结构性,用于塑造或重塑 DOM 的结构(下例,实现ngif的反向版本)
<p *appDemob="condition">23333</p>
// condition:boolean = false;
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appDemob]'
})
export class DemobDirective {
private hasView = false;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) {}
@Input() set appDemob(condition: boolean) {
if (!condition && !this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (condition && this.hasView) {
this.viewContainer.clear();
this.hasView = false;
}
}
}
3.ng g pipe pipeName 创建一个管道,是一些简单的函数,可以在模板表达式中用来接受输入值并返回一个转换后的值。下面的例子实现了字符串的指定长度显示
<p>{{str | lesslength:10 }}</p>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'lesslength'
})
export class LesslengthPipe implements PipeTransform {
transform(value: string, ...args: number[]): unknown {
return value.slice(0,args[0]);
}
}