Reputation: 31
Angular 7 - I'm trying to add .00 to the input field, this field is limited to accept only numbers and that works fine, however, I'd like to be able to add .00 in the same editable input field as soon as the user navigates to a different field in the form. I've added pipes as [(ngModel)]="appform.budgetvalue | number: '1.2-2'"
but it fails to load. I've added (change)="addDecimal($event)"
near the end but the method fails to trigger, some stackoverflow articles are suggesting to create a custom directive but unsure if that is the correct approach, based on the snippet below can some please suggest an approach, any help will be highly appreciated.
<div class="col-md-8">
<div class="form-group col-lg-6"
<div class="input-group">
<span class="input-group-addon">$</span>
<input name="budgetvalue" class="form-control" required digitOnly
decimal="true" decimalSeparator="." decimalDigitLimit="2" placeholder="0.00"
pattern="[0-9]+([.][0-9]+)?" isValidMoney
[(ngModel)]="appform.budgetvalue" #budgetvalue="ngModel">
</div>
<div *ngIf="(budgetvalue.touched)">
<div *ngIf="!budgetvalue?.valid">
<small class="text-danger">Please provide valid budget amount</small>
</div>
</div>
Upvotes: 0
Views: 3259
Reputation: 2420
Couple ways I can think of:
<input name="" ... (blur)="transform()" />
...
import { Component } from '@angular/core';
import { DecimalPipe } from '@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private decimalPipe: DecimalPipe) {}
decimal = "0";
transform() {
this.decimal = this.decimalPipe.transform(this.decimal, '1.2-2');
}
}
One caveat is that transform pipe returns a string. I've written this directive I've used in a past for reactive form or this one for template
<input [value]="appform.budgetvalue | number: '1.2-2'"/>
- this however probably doesnt work the way you expect but might give you some ideasUpvotes: 1