I'm currently trying to implement a validation rule for phone number on the form I'm working on. I'm using the ng2-tel-input library even though my form uses Angular 6.
The issue I got is that I cannot display an error message when the phone number is invalid.
Here is my HTML code for the moment :
<input class="form-control phoneField"
ng2TelInput
(hasError)="hasError($event)"
(intlTelInputObject)="telInputObject($event)"
type="text" pattern="^[\s0-9]*$" [required]="emailReq ? false :
!null" [(ngModel)]="phoneReq"
name="phone" #phone="ngModel" phoneValidator style="width: 100%
!important">
Typescript code
import * as ngTelInput from 'ng2-tel-input';
import 'intl-tel-input';
import 'intl-tel-input/build/js/utils';
export class phoneValidator {
@Input('ng2TelInputOptions') ng2TelInputOptions: any;
@Output('hasError') hasError: EventEmitter<boolean> = new EventEmitter();
@Output('ng2TelOutput') ng2TelOutput: EventEmitter<any> = new EventEmitter();
@Output('intlTelInputObject') intlTelInputObject: EventEmitter<any> = new
EventEmitter(); ngTelInput: any;
constructor (private el: ElementRef) {}
@HostListener('blur') onBlur() {
let isInputValid:boolean = this.isInputValid();
if (isInputValid) {
let telOutput = this.ngTelInput.intlTelInput("getNumber");
this.hasError.emit(isInputValid);
this.ng2TelOutput.emit(telOutput);
} else
{
this.hasError.emit(isInputValid);
}
}
isInputValid(): boolean {
return this.ngTelInput.intlTelInput('isValidNumber') ? true : false;
}
}
I'm new to Angular and don't understand why it's not working.
I tried to see if hasError was working with this :
hasError(obj) {
console.log('hasError: ', obj);
}
And it's working perfectly. If I'm putting an invalid phone number it display false and true if the phone number is valid. But the form still act as if there is a valid number even if it's clearly invalid and doesn't display an error message.
I hope I'm being clear and that someone can help me with this issue.
Finally got the answer, hope it can help someone :
Typescript :
Html :