3

I use ng2-tel-input with reactive form method (Angular).

Issue:
When i open flag dropdown and choose a value, it is working fine. Value is displayed into input correctly but country flag do not change and the default flag appear.

When I change value manually in input then flag changes automatically, otherwise default country flag displaying.

Example:
Value format: +917878747474
Selected country: India
Default country: us

when i press on set value. phone no set on input but flag remain same

html

 <form [formGroup]="form">
        <small class="phone-text">{{ placeHolder }}</small>
        <md-input-container class="full-width pt-0">
            <input type="text"
                   mdInput
                   formControlName="phone"
                   ng2TelInput
                   [ng2TelInputOptions]="{initialCountry: initialCountry}"
                   (hasError)="hasError($event)"
                   (ng2TelOutput)="hasOutPut($event)"
                   #phoneInput
                   maxlength="45"/>
        </md-input-container>
       <button type="button" (click)="setValue()">Set Value</button>
    </form>

Component

import {Attribute, Component, forwardRef, Input} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

@Component({
    selector: 'app-phone',
    templateUrl: './phone.component.html',
    styleUrls: ['./phone.component.scss']
})
export class PhoneComponent implements ControlValueAccessor, Validator {
    placeHolder = 'Default Value';
    initialCountry = 'us';
    form: FormGroup;

    constructor(private _fb: FormBuilder) {
        this._initForm();
    }

    setValue(): void {
        const phone = '+917878747416'
        this.form.setValue({phone: phone});
    }

    private _initForm(): void {
        this.form = this._fb.group({
            'phone': ['']
        });
    }

    hasError(event: any): void {
        if (!event && this.form.value.phone !== '') {
            this.form.get('phone').setErrors(['invalid_cell_phone', true]);
        }
    }

    hasOutPut(event: any): void {
        this.form.patchValue({phone: event});
    }
}

Any help would be appreciated.

Shailesh Ladumor
  • 7,052
  • 5
  • 42
  • 55
  • Can you provide a plunkr? – Olezt Jan 02 '18 at 13:18
  • i have created plunkr but i don't know how to add package in plunkr. i added but got 404. [plunkr](https://plnkr.co/edit/uEDUJa32MN5NSGCDzkAU?p=preview) – Shailesh Ladumor Jan 03 '18 at 04:43
  • I created a small project, creating a reactive form as you say and using the code you provided and everything is working fine. Can you provide some more code or any other info, otherwise I don't think we can help you. – Olezt Jan 03 '18 at 09:49
  • @Olezt i have updated Question and put my all code here. thanks for your time – Shailesh Ladumor Jan 03 '18 at 10:10
  • 1
    Ok, now the problem is clear. You change your value programmatically from the component and the flag do not change. I was able to reproduce this but I can't find any workaround. – Olezt Jan 03 '18 at 16:12
  • @Olezt thanks man. if any solution you will got post here. – Shailesh Ladumor Jan 04 '18 at 04:47
  • @ShaileshLadumor I'm having the same problem did you find the solution? – shamim khan May 13 '19 at 09:46

4 Answers4

0

HTML

<mat-form-field class="pd-mat-form-field-class" hideRequiredMarker>
 <label class="pd-mat-custom-label">{{"CELL_1" | translate }}</label>
 <mat-label></mat-label>
 <input ng2TelInput #intlInput 
   [ng2TelInputOptions]="cell1TelInput" 
   (hasError)="hasError1($event)" 
   (ng2TelOutput)="getNumberCellNo1($event)" 
   (intlTelInputObject)="cell1telInputObject($event)" 
   (countryChange)="onCell1CountryChange($event)" 
   type="text" 
   maxlength=14  class="pd-mat-form-input-margin"  
   matInput  name="cell_no1"
   formControlName = "cellnumber1" required>
</mat-form-field>

Ts

cell1TelInput = {
initialCountry: this.constant.defaultCountrycode, 
autoPlaceholder: 'polite',
nationalMode :true,
customPlaceholder: function(selectedCountryPlaceholder) {
  return 'Example : ' + selectedCountryPlaceholder;
}

  if (response.userCellNumbers[0] && response.userCellNumbers[0].cell_no) {
            this.cellnumber1 = response.userCellNumbers[0].cell_no;  
            this.cell_code1.setNumber(this.cellnumber1)     
          }

 getNumberCellNo1(e:any)
  {
    this.cell_code1.setNumber(e) 
    this.cellnumber1=e
  }

  public onCell1CountryChange(e: any) {
    this.cellnumber1DialCode =  e.dialCode;
    this.cell1TelInput.initialCountry = e.iso2
    this.cell_code1.setNumber("") 
  }

  public cell1telInputObject(obj) {
    this.cell_code1=obj
  }

  hasError1(event: any): void {
    if (!event && this.uploadForm.value.cellnumber1 ) {
    this.uploadForm.get('cellnumber1').setErrors(['invalid_cell_phone', true]);
    }
    }

  if (this.uploadForm.value.cellnumber1) {
      this.uploadForm.value.cellnumber1 = this.cellnumber1
      this.cellNumbers.push( {"cell_no": this.uploadForm.value.cellnumber1.replace(/\s/g, ""), "cell_type": 1});
    }`

    hasError() is used for validation
    The getNumber() will give you the country code and number as +919843133490.
    The setNumber() will set the country flag and place the number in input field.
    ng2TelInputOptions is used to initialize data

    Hope it helped. Any further queries can be asked.
Shailesh Ladumor
  • 7,052
  • 5
  • 42
  • 55
0

This is crazy hack but worked:

So, if you just want to change the flag based on the input value, the component itself already detects keyup events and sets the flag based on the dialCode (e.g. if you start typing "+49", it would set the German flag).

Based on that, if you set the input field programmatically, it will not detect this keyup event, so I decided to hack it.

This answer helped me how to do that: Trigger keyup event in Angular 5 TypeScript

Bind your input with ViewChild:

@ViewChild('phoneInput')
phoneInput: ElementRef;

Trigger a fake keyup event:

setValue(): void {
  const phone = '+917878747416'
  this.form.setValue({phone: phone});
  this.phoneInput.nativeElement.dispatchEvent(
    new KeyboardEvent('keyup', { bubbles: true })
  );
}

Worked out pretty smoothly for me.

Marco Nascimento
  • 832
  • 8
  • 15
0
<input type="text"
  ng2TelInput
  [ng2TelInputOptions]="{initialCountry: 'in'}"
  (hasError)="hasError($event)"
  (ng2TelOutput)="getNumber($event)"
  (intlTelInputObject)="telInputObject($event)"
  (countryChange)="onCountryChange($event)" />

(The HTML above is from https://github.com/gauravsoni119/ng2-tel-input)

 inputObj: any;

  telInputObject(obj, val) {
    this.inputObj = obj;
    if (this.contactNumber) {
      obj.setNumber(this.contactNumber);
    }
  }

on ngOnInit() check if inputObj is present if not set it

ngOnInit(){
    if(inputObj){
       inputObj.setNumber('+91987654321');
    }
}

setNumber will automaticaly detect flag

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
0

This works for me:

telInputObject(obj) {
    obj.setCountry("br");
    obj.setNumber("xxxxxx");
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45