Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何对数据值使用指令?_Angular_Angular Directive - Fatal编程技术网

Angular 如何对数据值使用指令?

Angular 如何对数据值使用指令?,angular,angular-directive,Angular,Angular Directive,如何对数据值使用指令 <div class="col-12 data" appPhoneNumber> {{data.phoneNumber}} </div> 在没有角度输入的情况下,不能将输入控件与ngControl一起使用,这就是为什么会出现无提供程序错误。对于简单的显示值,需要管道。首先将转换函数提取为可重用的函数: function formatPhoneNumber(val) { let newVal = val.replace(/\D/g,

如何对数据值使用指令

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

在没有角度输入的情况下,不能将输入控件与ngControl一起使用,这就是为什么会出现无提供程序错误。对于简单的显示值,需要管道。首先将转换函数提取为可重用的函数:

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;
}
将其声明/导入为正常,然后按如下方式使用:

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

{{data.phoneNumber}phone}

此指令应该做什么?它的代码在哪里?您应该使用
@指令
注释并指定具有相同名称的
@输入
@指令({选择器:'[appPhoneNumber]})
然后
@Input('appPhoneNumber')appPhoneNumber在指令的类声明中。@hilnius我尝试使用输入,但它仍然给我相同的结果error@bryan60更新。它只是应该在电话号码上加上点。像这样:xxx.xxx.xxxxIn输入或仅作为显示值?我是否能够使用管道同时用于输入和显示值?或者我必须创建一个指令和一个管道吗?您需要一个用于显示数据的管道和一个用于格式化输入的指令。它们是根本不同的,您可以做的最好的事情是拉出实际的格式化函数,并按照建议在两个位置使用它。
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>