角度5管道装饰不起作用

时间:2018-05-01 15:12:50

标签: angular pipe angular-pipe

我创建了一个名为Pipe的角度trim。此管道旨在从字符串中删除最后一个字符。这是我的管道类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 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:-1)

这是一个非常保守的版本,它可以捕获任何错误。

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

总的来说,你的代码看起来是正确的地方,但我看到了几个问题:

  1. 转换应始终返回字符串
  2. 尝试/捕捉内脏是个好主意,所以你有机会看到任何错误。
  3. 我找到了将在随机场所使用的较低级别的东西,最好是“防御性地”编写这些东西,以便在任何可能被抛出的东西中生存。