如何在角度4中为DecimalPipe编写自定义指令

时间:2017-10-31 04:48:57

标签: angular

我创建了像

这样的货币指令
import { Directive, HostListener, ElementRef, OnInit } from "@angular/core";
import { MyCurrencyPipe } from "./my-currency.pipe";

@Directive({ selector: "[myCurrencyFormatter]" })
export class MyCurrencyFormatterDirective implements OnInit {

    private el: any;

    constructor(
        private elementRef: ElementRef,
        private currencyPipe: MyCurrencyPipe
    ) {
        this.el = this.elementRef.nativeElement;

    }

    ngOnInit() {
        this.el.value = this.currencyPipe.transform(this.el.value);
    }

    @HostListener("focus", ["$event.target.value"])
    onFocus(value) {
        this.el.value = this.currencyPipe.parse(value); // opossite of transform
    }

    @HostListener("blur", ["$event.target.value"])
    onBlur(value) {
        this.el.value = this.currencyPipe.transform(value);
    }

}

我点了这个链接http://plnkr.co/edit/rKq8yCoNhwXFozKsKPZf?p=preview

但如何动态创建DecimalPipe

示例十进制管道

@Component({
  selector: 'number-pipe',
  template: `<div>  

    <p> {{pi | number:'1.2-2'}}</p>
  </div>`
})
export class NumberPipeComponent {
  pi: number = 3;
}

如果我在文本框中输入3,那么我想在ng-model更改事件中获得3.00。

0 个答案:

没有答案