2017-08-17 44 views
2

我正在嘗試做一個可以簡化錢數輸入的Angular(v2,現在改名爲Angular)組件。爲此,我想在單位輸入後顯示「.00」佔位符。然後,當用戶鍵入「。」時或「,」,佔位符會放棄讓他輸入小數。有小數點佔位符的角度貨幣輸入

像這樣: 1-用戶類型單位在第一

1- The user type units at first

2-然後用戶鍵入 '' 或 '' :

2- The user then type ',' or '.

我已經添加了一個跨度來定位絕對,但它不會跟隨打字的變化,並使其檢測用戶輸入和字體大小,以確定它的位置是有點乏味。

此外,我嘗試使用自定義管道,但是我想要返回格式化HTML,因爲我想要的是消毒並顯示爲文本。

這裏基本上是我做了什麼:

<span> 
     <custom-field-text 
      [placeholder]="placeholderValue" 
      [pattern]="pattern" 
      [value]="value" 
      (change)="onChange($event)"> 
     </custom-field-text> 
     <span [hidden]="!decimalPlaceholder" [ngClass]='setColor()'> {{0 | number:'1.2' | slice:1}} </span> 
</span> 

而且在我的.ts組件定義我寫了一個onchange方法:

onChange(value: string): void { 

     if(value.indexOf(',') >= 0 || value.indexOf('.') >= 0) { 
     this.decimalPlaceholder = true; 
     this.placeholderValue = ""; 
     } else { 
     this.decimalPlaceholder = false; 
     this.placeholderValue = ".00"; 
     } 
     this.value = value; 
    } 

佔位符輸入改變之前纔會顯示。如果我像我這樣做一個跨度絕對位置,位置必須從字符串大小和字體大小計算,我認爲它是過度的...

你知道一個技巧或什麼我可以使用爲了達成這個 ?謝謝 !

回答

0

HTML

<input type="text" ng-keypress="($event.which >= 48)?changePlaceholder():0" placeholder="{{vm.modelP}}"> 

ANGULAR

vm.modelP="" ;   
changePlaceholder(){ 
    vm.modelP=",00"; 
    } 
+0

對不起,我會發布我目前的代碼,所以你們將能夠看到我所做的。我已經在「ngModelChange」方法中隱藏或顯示自定義佔位符。它不會與真正的佔位符一起使用,因爲它只在字段無效時顯示:( – Alex

0

我總算讓它工作,但我仍然有一個問題。當它不是佔位符時,我必須使輸入文本透明。

在我的部分,我所做的:

<span> 
     <custom-field-text 
      class="custom-field-currency-input" 
      [placeholder]="'0,00'" 
      [pattern]="pattern" 
      [value]="value" 
      (change)="onChange($event)"> 
     </custom-field-text> 
     <span class="decimal-placeholder"> 
      <span>{{value}}</span> 
      <span [ngClass]='setColor()' *ngIf="placeholderVisibility">{{0 | number:'1.2' | slice:1}}</span> 
     </span> 
    </span> 

有了這個SCSS文件:

span { 
     display: table-cell; 
     vertical-align: middle; 

     span.decimal-placeholder { 
      position: absolute; 
      left: 0px; 
      top: 40%; 
      z-index: 1; 

      span { 
       display: table-cell; 
      } 

      span:last-child { 
       padding-left: -10px; 
       overflow: visible; 
      } 
     } 
    } 

這的onChange功能(placeholderVisibility是默認爲false,因爲HTML佔位符時生效字段無效):

onChange(value: string): void { 

     if(value.indexOf(',') >= 0 || value.indexOf('.') >= 0 || value === "") { 
     this.placeholderVisibility = false; 
     } else { 
     this.placeholderVisibility = true; 
     } 
     this.placeholderValue = value; 
     this.value = value; 

    } 

而且我工作:)我的「虛擬輸入placehol der「在我打字的同時正在移動。有一個輕微的疊加壽,這就是爲什麼我想隱藏輸入文字。