- 创建自定义管道:
- 使用Angular CLI生成管道:
ng generate pipe customFormat
。
- 在生成的管道文件(如
custom - format.pipe.ts
)中编写转换逻辑:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customFormat'
})
export class CustomFormatPipe implements PipeTransform {
transform(value: { name: string; age: number }): string {
return `Name is ${value.name}, age is ${value.age}`;
}
}
- 创建自定义指令:
- 使用Angular CLI生成指令:
ng generate directive customDisplay
。
- 在生成的指令文件(如
custom - display.directive.ts
)中编写指令逻辑:
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import { CustomFormatPipe } from './custom - format.pipe';
@Directive({
selector: '[appCustomDisplay]'
})
export class CustomDisplayDirective implements OnInit {
@Input() dataObject: { name: string; age: number };
constructor(private el: ElementRef, private customFormatPipe: CustomFormatPipe) {}
ngOnInit() {
if (this.dataObject) {
const formattedValue = this.customFormatPipe.transform(this.dataObject);
this.el.nativeElement.textContent = formattedValue;
}
}
}
- 在模块中声明:
- 在相关的Angular模块(如
app.module.ts
)中声明管道和指令:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { AppComponent } from './app.component';
import { CustomFormatPipe } from './custom - format.pipe';
import { CustomDisplayDirective } from './custom - display.directive';
@NgModule({
declarations: [
AppComponent,
CustomFormatPipe,
CustomDisplayDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
- 在模板中使用:
- 在组件的模板(如
app.component.html
)中使用指令:
<div appCustomDisplay [dataObject]="{name: 'John', age: 30}"></div>