首页 文章

角度5管道装饰不起作用

提问于
浏览
0

我创建了一个名为 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 { }

2 回答

  • -1

    当bg.name为falsy时,你只在空字符串上使用管道 . 通过移动括号修复:

    <span>{{(bg.name ? bg.name + ', ' : '') | trim}}</span>
    

    顺便说一句,如果您将整个逻辑移动到管道或预先格式化字符串,然后将其传递给模板(即在组件或服务代码中),您将获得性能优势 . Angular在每个更改检测周期中运行模板插值中的所有评估,而纯管道将被缓存,直到输入值更改为止 .

  • 3

    这是一个非常保守的版本,它应该捕获任何错误 .

    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;
        }
      }
    }
    

    总体而言,您的代码看起来像是在正确的位置,但我看到了几个问题:

    • 转换应始终返回一个字符串

    • 尝试/捕捉内脏是一个好主意,所以你有机会看到任何错误 .

    我找到了将在随机场所使用的较低级别的东西,这是一个好主意,他们“防御性地”编写它们以生存任何可能被抛出的东西 .

相关问题