目前我正在使用带有primeng的Angular 5进行项目。我正在尝试以 react 形式将来自下拉列表的国家/地区附加到电话号码中。当我从下拉列表中选择国家代码时遇到问题它不会附加到我必须传递值的电话号码。
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
profileForm = new FormGroup({
phoneNumber: new FormControl('')
})
onSubmit(phoneValue){
console.log(phoneValue)
}
onCountryChange(event){
console.log(event);
}
}
<form [formGroup]="profileForm" (ngSubmit)="onSubmit(profileForm.value)">
<div class="ui-g-12 ui-xs-12 ui-sm-12 ui-md-12 ui-lg-4 responsiveForIpad">
<div class="ui-g passengerMainDetails">
<div class="ui-g-12 ui-xs-12 ui-sm-12 ui-md-12 ui-lg-12">
<label> Contact Number *</label>
</div>
<div class="ui-g-12 ui-xs-12 ui-sm-12 ui-md-12 ui-lg-12">
<input type="text" formControlName="phoneNumber" ng2TelInput (countryChange)="onCountryChange($event)" placeholder="Please Enter the Phone number here"/>
</div>
</div>
</div>
</form>
最佳答案
首先,您需要有一个有效的表单控件,它被传递给 ng2TelInput
而你有phoneName
在你的 TS 和 MobileNo
在您的 HTML 中。
之后,该值将绑定(bind)到 from 控件,并且可以在使用 this.profileForm.get('phoneNumber').value
提交时访问.这将返回一个对象,您可以使用 internationalNumber
获取该数字如果你想用 +
格式化和空格,或使用 number
/nationalNumber
如果您需要它而不需要格式化。
为此,您将不需要 onCountryChange
发射器,因为我们将在提交时获得数字(除非您需要监听器来做其他事情)。
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
profileForm = new FormGroup({
phoneNumber: new FormControl('')
});
onSubmit(){
console.log(this.phoneForm.get('phone').value.internationalNumber);
}
}
<form [formGroup]="profileForm" (ngSubmit)="onSubmit(profileForm.value)">
<div class="ui-g-12 ui-xs-12 ui-sm-12 ui-md-12 ui-lg-4 responsiveForIpad">
<div class="ui-g passengerMainDetails">
<div class="ui-g-12 ui-xs-12 ui-sm-12 ui-md-12 ui-lg-12">
<label> Contact Number *</label>
</div>
<div class="ui-g-12 ui-xs-12 ui-sm-12 ui-md-12 ui-lg-12">
<input type="text" formControlName="phoneNumber" ng2TelInput placeholder="Please Enter the Phone number here"/>
</div>
</div>
</div>
</form>
关于angular - 如何使用primeng将电话号码附加到 Angular 5的国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64213358/