2017-07-19 165 views
0

掩蓋離子輸入元件的最佳方法是什麼?例如電話號碼......這樣的事情:離子3輸入掩膜

<ion-input type="tel" placeholder="celular" name="celular" 
[(ngModel)]="phone_number" required 
mask="(**)*****-****" ></ion-input> 

回答

0
  • 3個步驟:

  • ==> 1 - 創建一個指令。

  • ==> 2 - 通過放入聲明數組導入到主模塊。
  • ==> 3 - 在html文件中使用指令。

步驟1
import { Directive, Attribute } from '@angular/core'; 
    import { NgModel } from '@angular/forms'; 
    @Directive({ 
     selector: '[mask]', 
     host: { 
      '(keyup)': 'onInputChange($event)' 
     }, 
     providers: [NgModel] 
    }) 
    export class Mask { 
     maskPattern: string; 
     placeHolderCounts: number; 
     dividers: string[]; 
     modelValue: string; 
     viewValue: string; 

     constructor(
      public model: NgModel, 
      @Attribute("mask") maskPattern: string 
     ) { 
      this.dividers = maskPattern.replace(/\*/g, "").split(""); 
      this.dividers.push(" "); 
      this.generatePattern(maskPattern); 
    } 

    onInputChange(event) { 
     this.modelValue = this.getModelValue(event); 
     let stringToFormat = this.modelValue; 
     if (stringToFormat.length < 10) { 
      stringToFormat = this.padString(stringToFormat); 
     } 

     this.viewValue = this.format(stringToFormat); 
     this.writeValue(event.target, this.viewValue); 
    } 

    writeValue(target, value) { 
     return target.value = value; 
    } 

    generatePattern(patternString) { 
     this.placeHolderCounts = (patternString.match(/\*/g) || []).length; 
     for (let i = 0; i < this.placeHolderCounts; i++) { 
      patternString = patternString.replace('*', "{" + i + "}"); 
     } 
     this.maskPattern = patternString; 
    } 

    format(s) { 
     var formattedString = this.maskPattern; 
     for (let i = 0; i < this.placeHolderCounts; i++) { 
      formattedString = formattedString.replace("{" + i + "}",   s.charAt(i)); 
      } 
      return formattedString; 
     } 

     padString(s) { 
      var pad = "   "; 
      return (s + pad).substring(0, pad.length); 
     } 

     getModelValue(event) { 
      var modelValue = event.target.value; 
      for (var i = 0; i < this.dividers.length; i++) { 
       while (modelValue.indexOf(this.dividers[i]) > -1) { 
        modelValue = modelValue.replace(this.dividers[i], ""); 
       } 
      } 
      return modelValue; 
     } 
    } 
  • 第二步
    import { Mask } from'./Mask'; 
    @NgModule({ 
        declarations: [ 
        MyApp, 
        HomePage, 
        Mask 
    ], 
    
  • 步驟3
    <form> 
        <ion-list> 
         <ion-item> 
         <ion-input type="text" mask="(**)****-****"></ion-input> 
         </ion-item> 
        </ion-list> 
        <button ion-button block type="submit">Save</button> 
        </form> 
    
+0

謝謝你的回答......你認爲這是做這件事的最好方法嗎? –

+0

使用'mask =「****** - **** - ******」'去掉前兩組中的字符是痛苦的:/ – Luckylooke

+0

這是一個簡單和普通功能的很多代碼。一定會有更好的辦法。 –