首页 > 解决方案 > 如何在 Angular Material V6 中列出国际电话号码?

问题描述

我正在开发一个使用 Angular Material V6 的应用程序。我想在材料组件文本框中列出带有标志的国际电话号码。我在互联网上搜索并找到了一个 npm 模块,但它使用的是引导文本组件。我添加了一个截图来看看它。Bootstrap 与 Angular 材质文本框组件不同。

现在它是:

在此处输入图像描述

角材料成分:

在此处输入图像描述

示例代码:

<mat-form-field color="warn" class="form-field-width">
 <int-phone-prefix matInput [locale]="'es'"></int-phone-prefix>
</mat-form-field>

错误:

ERROR 错误:mat-form-field 必须包含 MatFormFieldControl。

请给我你的建议。提前致谢。

标签: javascriptjqueryangular5angular-material2

解决方案


我让它使用不同的依赖项,它是ng2-tel-input。示例源代码(在此之上记得遵循 repo 中提供的“安装”):

联系人.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>

联系人.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 {}

联系人.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]);
    }
  }
}

推荐阅读