我创建了一个名为trim
的角度Pipe
。此管道旨在从字符串中删除最后一个字符。这是我的管道类TrimPipe
。在 HTML 中使用管道时,控制台不会记录值。 这里的 HTML 用法 -
<ng-container *ngFor="let bg of backgrounds.preferred">
<span>{{bg.name ? (bg.name + ', ') : '' | trim}}</span>
</ng-container>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'trim'
})
export class TrimPipe implements PipeTransform {
transform(value: any, args?: any): any {
console.log(value, args, 'Pipes');
return value.toString().substring(0, value.length - 1);
}
}
我的app.module.ts
文件 -
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
// Custom
import {AppComponent} from './app.component';
import {CommonService} from './shared/services/common.service';
import {DirectivesModule} from './shared/directives/directives.module';
import {PipeModule} from './shared/pipe/pipe.module';]
@NgModule({
declarations: [
AppComponent
],
imports: [
DirectivesModule,
PipeModule,
HttpClientModule,
BrowserModule,
BrowserAnimationsModule,
NgSelectModule,
FormsModule
],
providers: [CommonService],
bootstrap: [AppComponent]
})
export class AppModule {
}
我的pipe.module.ts
——
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TrimPipe } from './trim.pipe';
@NgModule({
imports: [
CommonModule
],
declarations: [TrimPipe],
exports: [TrimPipe]
})
export class PipeModule { }
<span>{{(bg.name ? bg.name + ', ' : '') | trim}}</span>
顺便说一下,如果在将字符串传递到模板(即在组件或服务代码中(之前将整个逻辑移动到管道或预先格式化字符串,则会获得性能优势。Angular 在每个更改检测周期运行模板插值中的所有评估,而纯管道被缓存,直到输入值发生变化。
这是一个非常保守的版本,它应该可以捕获任何错误。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'trim'})
export class TrimPipe implements PipeTransform {
transform(inValue: any): string {
let value = '';
try {
value = inValue.toString();
console.log('TrimPipe: >>' + value + '<<');
return value.substring(0, value.length - 1);
} catch (err) {
console.log(err);
return value;
}
}
}
总体而言,您的代码看起来要到正确的位置,但是我看到了几个问题:
- 转换应始终返回一个字符串
- 尝试/捕捉内脏是个好主意,这样你就有机会看到任何错误。
我发现对于将在随机位置使用的较低级别的东西,最好"防御性"地编写它们,以便在任何可能扔给他们的东西中幸存下来。