Reputation: 143
I am using angular material(https://material.angular.io/components/form-field/overview) for input.
I want to auto add '+6' when user click on the field to insert phone number
Currently the '6' prefix only display in front of the form.
<mat-form-field>
<span matPrefix>6 </span>
<input matInput placeholder="Phone Number (Eg: 60181345689)" required formControlName="contactNo [value]="field_contact">
</mat-form-field>
Upvotes: 2
Views: 11445
Reputation: 945
Since you are using ReactiveForms
, you should use methods it provides for this...
Upvotes: 1
Reputation: 467
Adding the matPrefix
directive to an element inside the will designate it as the prefix. It will be included within the visual container that wraps the form control as per the Material specification.
<form class="example-form">
<mat-form-field class="example-full-width">
<span matPrefix>+6 </span>
<input type="tel" matInput placeholder="Phone Number">
</mat-form-field>
</form>
Upvotes: 0
Reputation: 42576
You can make use of the focusin
event binding.
On your component.html,
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="Click here" (focusin)="addPrefix($event)" [value]="inputValue">
</mat-form-field>
</form>
And on your component.ts,
inputValue: string = '';
addPrefix(event) {
this.inputValue = '+6'
}
This will add the '+6' on the input when the user clicks on the input.
I have made a demo for you over here.
Upvotes: 0
Reputation:
I assume you're using the pattern
validator :
<span matPrefix *ngIf="!myForm.get('contactNo').hasError('pattern')">
If you want to show it only on focus :
<span matPrefix *ngIf="!myForm.get('contactNo').hasError('pattern') && activeDocumentElement === phoneNumber">
<input #phoneNumber matInput placeholder="Phone Number (Eg: 60181345689)" required formControlName="contactNo [value]="field_contact">
Where
get activeDocumentElement() { return document.activeElement; }
Upvotes: 0