2

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

enter image description here

Currently the '6' prefix only display in front of the form.

<mat-form-field>
   <span matPrefix>6&nbsp;</span>
   <input matInput placeholder="Phone Number (Eg: 60181345689)"  required formControlName="contactNo [value]="field_contact">
</mat-form-field>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Firdaus
  • 143
  • 5
  • 22

4 Answers4

0

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; }
0

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.

wentjun
  • 40,384
  • 10
  • 95
  • 107
0

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 &nbsp;</span>
    <input type="tel" matInput placeholder="Phone Number">
  </mat-form-field>     
</form>
nircraft
  • 8,242
  • 5
  • 30
  • 46
Zoha Irshad
  • 427
  • 5
  • 5
0

Since you are using ReactiveForms, you should use methods it provides for this...

See stackblitz example

tony
  • 834
  • 5
  • 10