如何对数据值使用指令?

时间:2019-07-25 19:55:15

标签: angular angular-directive

如何对数据值使用指令?

<div class="col-12 data" appPhoneNumber>
    {{data.phoneNumber}}
</div>

appPhoneNumber是我的指令,data.phoneNumber是我要在其上使用的值。我以这种方式尝试过,但出现错误:

Error: StaticInjectorError(AppModule)[PhoneNumberDirective -> NgControl]: StaticInjectorError(Platform: core)[PhoneNumberDirective -> NgControl]: NullInjectorError: No provider for NgControl!

我有点不知所措,我对指令没有太多经验

编辑以包含指令代码:

@Directive({
  selector: '[appPhoneNumber]'
})
export class PhoneNumberDirective {

  constructor(public ngControl: NgControl) { }
  @Input('appPhoneNumber') appPhoneNumber;

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event);
  }

  onInputChange(event){
    let newVal = event.replace(/\D/g, '');
    if(newVal.length === 0){
      newVal = '';
    } else if(newVal.length<=3){
      newVal = newVal;
    } else if(newVal.length<=6){
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '$1.$2');
    } else if(newVal.length<=10){
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1.$2.$3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1.$2.$3');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}

1 个答案:

答案 0 :(得分:1)

您不能在没有角度输入的情况下使用注入了ngControl的输入控件,这就是为什么会出现no provider错误的原因。对于简单的显示值,您需要一个管道。首先将您的转换函数提取为可重用的东西:

function formatPhoneNumber(val) {
    let newVal = val.replace(/\D/g, '');
    if(newVal.length === 0){
      newVal = '';
    } else if(newVal.length<=3){
      newVal = newVal;
    } else if(newVal.length<=6){
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '$1.$2');
    } else if(newVal.length<=10){
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1.$2.$3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1.$2.$3');
    }
    return newVal;
}

并将其放入您的指令中,然后编写一个也使用它的管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'phone'})
export class PhonePipe implements PipeTransform {
  transform(value: string): string {
    return formatPhoneNumber(value);
  }
}

声明/正常导入,然后像这样使用它:

<div class="col-12 data">
    {{data.phoneNumber | phone}}
</div>