我正在开发一个使用 Angular Material V6 的应用程序。我想在 Material 组件文本框中列出带有标志的国际电话号码。我在互联网上搜索并找到了一个 npm 模块,但它使用的是引导文本组件。我添加了一个屏幕截图来查看它。 Bootstrap 不同于 Angular Material 文本框组件。
现在是:
Angular Material 组件:
示例代码:
<mat-form-field color="warn" class="form-field-width">
<int-phone-prefix matInput [locale]="'es'"></int-phone-prefix>
</mat-form-field>
错误:
ERROR Error: mat-form-field must contain a MatFormFieldControl.
请给我你的建议。提前致谢。
最佳答案
我让它在不同的依赖项下工作,它是 ng2-tel-input .示例源代码(最重要的是,请记住遵循存储库中提供的“安装”):
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]);
}
}
}
关于javascript - 如何在 Angular Material V6 中列出国际电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50692528/