角度-在括号中显示负值并保持“类型:数字”

时间:2018-08-08 23:19:49

标签: angular typescript

我正在处理百分比图,并且我想将负数的格式设置为括号内而不是负号。我可以找到如何使用管道进行此操作...但是,只有在我拥有货币管道之后,该管道才能将数字类型转换为字符串。有没有办法让类型保持数字并用括号括住负号?这是管道:

export class MinusToParensPipe implements PipeTransform {
    transform(value: any, args?: any): any {
        return value.charAt(0) === '-' ?
            '(' + value.substring(1, value.length) + ')' :
            value;
    }
}

1 个答案:

答案 0 :(得分:0)

如果不需要管道,请尝试以下操作:

HTML

<p [ngClass]="{'setPerens' : isNegitive(YourNumericalValue)}">{{YourNumericalValue | negToPos }}</p>

SASS

.setPerens {
 :before {
  content: '(';
 :after {
  content: ')';
 }
}

.TS

isNegitive(val: number): boolean {
 if (val < 0) {
  return true;
 } else {
  return false
 }
}

编辑1:

要摆脱负号,您现在可以像这样使用Pipe:

@Pipe({
  name: 'negToPos'
})
export class NegToPosPipe implements PipeTransform {
  transform(val: number): number {
    return Math.abs(val);
  }
}
相关问题