角度:当用户单击输入文本时,如何在输入中添加前缀+6

时间:2019-04-05 09:35:00

标签: angular angular6 angular5

  1. 我正在使用角形材料(https://material.angular.io/components/form-field/overview)进行输入。

  2. 我想在用户单击字段以插入电话号码时自动添加“ +6”

enter image description here

  1. 当前,“ 6”前缀仅显示在表单的前面。
<mat-form-field>
   <span matPrefix>6&nbsp;</span>
   <input matInput placeholder="Phone Number (Eg: 60181345689)"  required formControlName="contactNo [value]="field_contact">
</mat-form-field>

3 个答案:

答案 0 :(得分:0)

我假设您正在使用pattern验证程序:

<span matPrefix *ngIf="!myForm.get('contactNo').hasError('pattern')">

如果只想显示焦点:

<span matPrefix *ngIf="!myForm.get('contactNo').hasError('pattern') && activeDocumentElement === phoneNumber">
<input #phoneNumber matInput placeholder="Phone Number (Eg: 60181345689)"  required formControlName="contactNo [value]="field_contact">

哪里

get activeDocumentElement() { return document.activeElement; }

答案 1 :(得分:0)

您可以使用focusin事件绑定。

在您的component.html上,

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Click here" (focusin)="addPrefix($event)" [value]="inputValue">
  </mat-form-field>
</form>

在您的component.ts上,

inputValue: string = '';

addPrefix(event) {
  this.inputValue = '+6'
}

这将在用户单击输入时在输入上添加“ +6”。

我已通过here为您制作了一个演示。

答案 2 :(得分:0)

matPrefix指令添加到内的元素将把它指定为前缀。根据材料规范,它将包含在包装表单控件的可视容器中。

<form class="example-form">
  <mat-form-field class="example-full-width">
    <span matPrefix>+6 &nbsp;</span>
    <input type="tel" matInput placeholder="Phone Number">
  </mat-form-field>     
</form>