【问题标题】:angular input paste issue in reactive form + directive反应形式+指令的角度输入粘贴问题
【发布时间】:2021-04-27 13:47:22
【问题描述】:

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

您可以在 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);
  }
}

【问题讨论】:

    标签: angular angular2-directives reactive-forms


    【解决方案1】:

    您可以使用 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();
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2019-03-02
      • 2021-01-18
      • 2020-08-18
      • 1970-01-01
      相关资源
      最近更新 更多