ng2-tel-input:手动更改输入时,国家/地区标志不会自动更改

时间:2018-01-02 11:08:32

标签: angular

我将ng2-tel-input与反应式表格方法(Angular)一起使用。

问题:
当我打开标记下拉列表并选择一个值时,它工作正常。 值正确显示在输入中,但国家标志不会更改,并显示默认标志。

当我在输入中手动更改值时,标志会自动更改,否则显示默认的国家/地区标志。

示例:
值格式: +917878747474
所选国家:印度
默认国家/地区:我们

当我按下设定值时。手机没有设置输入但标志保持不变

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>

组件

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

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

这是疯狂的骇客,但有效:

因此,如果您只是想根据输入值更改标志,则组件本身已经检测到键入事件,并根据dialCode设置了标志(例如,如果您开始输入“ +49”,它将会设置德国国旗)。

基于此,如果您以编程方式设置输入字段,它将不会检测到该keyup事件,因此我决定对其进行破解。

这个答案帮助我做到了: Trigger keyup event in Angular 5 TypeScript

使用ViewChild绑定您的输入:

@ViewChild('phoneInput')
phoneInput: ElementRef;

触发一个伪造的keyup事件:

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

对我来说很顺利。

答案 2 :(得分:0)

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

(上面的HTML来自https://github.com/gauravsoni119/ng2-tel-input

 inputObj: any;

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

ngOnInit()上检查inputObj是否存在(如果未设置)

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

setNumber将自动检测标志