【问题标题】:ng2-tel-input: Country flag do not change automatically when manually change inputng2-tel-input:手动更改输入时,国家标志不会自动更改
【发布时间】:2018-06-12 02:15:30
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 你能提供一个plunkr吗?
  • 我已经创建了 plunkr,但我不知道如何在 plunkr 中添加包。我添加但得到 404。plunkr
  • 我创建了一个小项目,按照您的说法创建了一个反应式表单,并使用您提供的代码,一切正常。您能否提供更多代码或任何其他信息,否则我认为我们无法为您提供帮助。
  • @Olezt 我已经更新了问题并将我的所有代码放在这里。感谢您的宝贵时间
  • 好的,现在问题很清楚了。您以编程方式从组件更改您的值,并且标志不会更改。我能够重现此问题,但找不到任何解决方法。

标签: angular


【解决方案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.

【讨论】:

    【解决方案2】:

    这是一个疯狂的 hack,但有效:

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

    基于此,如果您以编程方式设置输入字段,它不会检测到这个 keyup 事件,所以我决定破解它。

    这个答案帮助我如何做到这一点: Trigger keyup event in Angular 5 TypeScript

    将您的输入与 ViewChild 绑定:

    @ViewChild('phoneInput')
    phoneInput: ElementRef;
    

    触发一个虚假的按键事件:

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

    对我来说很顺利。

    【讨论】:

      【解决方案3】:
      <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 会自动检测标志

      【讨论】:

        猜你喜欢
        • 2022-06-17
        • 1970-01-01
        • 2020-01-05
        • 2013-10-09
        • 2018-01-25
        • 1970-01-01
        • 2015-05-09
        • 2011-11-14
        • 1970-01-01
        相关资源
        最近更新 更多