I am working on an application that uses Angular Material V6. I want to list out the international phone number with flags in Material component text box. I searched the Internet and found an npm module but it was using bootstrap text component. I added a screenshot taking a look at it. Bootstrap differs from angular material text box component.
Now it is:
Angular material component:
Sample code:
<mat-form-field color="warn" class="form-field-width">
<int-phone-prefix matInput [locale]="'es'"></int-phone-prefix>
</mat-form-field>
ERROR:
ERROR Error: mat-form-field must contain a MatFormFieldControl.
please give me your suggestion. Thanks in advance.
I got it working with different dependency, it's ng2-tel-input. Sample source code (on top of this remember to follow the "Installation" available in the repo):
contact.component.html
<mat-form-field appearance="outline">
<input
matInput
ng2TelInput
[ng2TelInputOptions]="{initialCountry: 'us'}"
formControlName="formControlPhone"
(hasError)="hasError($event)" />
<mat-error
*ngIf="
!contactForm.get('formControlPhone').valid &&
contactForm.get('formControlPhone').touched
"
>This is an <strong>invalid</strong> phone number.
</mat-error>
</mat-form-field>
contact.module.ts
import { NgModule } from '@angular/core';
import { ContactComponent } from './contact/contact.component';
import { CommonModule } from '@angular/common'
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
MatFormFieldModule,
MatInputModule
} from '@angular/material';
import {Ng2TelInputModule} from 'ng2-tel-input';
@NgModule({
declarations: [ContactComponent],
imports: [
FormsModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
Ng2TelInputModule
],
})
export class ContactModule {}
contact.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.scss']
})
export class ContactComponent {
public contactForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.contactForm = this.formBuilder.group({
formControlPhone: ['', Validators.required]
});
}
hasError(event: any): void {
if (!event && this.contactForm.value.formControlPhone !== '') {
this.contactForm.get('formControlPhone').setErrors(['invalid_cell_phone', true]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With