反应形式+指令的角度输入粘贴问题

问题描述

我在使用响应式表单中的指令粘贴文本输入时遇到问题。

您可以在 https://stackblitz.com/edit/angular-klzz2y 看到问题。在该文本框中输入诸如“$%FDG%$^GWE43j52409543”之类的内容,然后查看文本框中反映的新值与反应形式中的值之间的差异!

sample output (image)

这是指令

@Directive({
  selector: "[appEmailPart]"
})
export class EmailPartDirective {
  constructor(private _el: ElementRef) {}

  @HostListener("input",["$event"]) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;
    this._el.nativeElement.value = initalValue.replace(
      /[^A-Za-z0-9\.\ _\-]*/g,""
    );
    if (initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }
}

这是html


<form [formGroup]="addUserDetailForm" (ngSubmit)="onSaveClick()">
<div>
    <input type="text" formControlName="emailPart" appEmailPart />
</div>
<div>
    <button type="submit">Save</button>
</div>
</form>

{{
  addUserDetailForm.value.emailPart
}}

还有表格

import { Component,OnInit } from "@angular/core";
import { FormBuilder,FormGroup,Validators } from "@angular/forms";

@Component({
  selector: "my-app",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  name = "Angular";

  addUserDetailForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.addUserDetailForm = this.fb.group({
      emailPart: ["",[Validators.required]],});
  }

  onSaveClick() {
    console.log('email part:',this.addUserDetailForm.value.emailPart);
  }
}

解决方法

您可以使用 setValue() 方法更新响应式表单控件。

constructor(private _el: ElementRef,private _control : NgControl) {}

@HostListener("input",["$event"]) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;
    this._control.control.setValue(initalValue.replace(
      /[^A-Za-z0-9\.\ _\-]*/g,""
    ));
    if (initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }