Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

angular input paste issue in reactive form + directive

I am facing issues in pasting in text inputs with directive in Reactive forms.

You could see the issue at https://stackblitz.com/edit/angular-klzz2y . Input something in that textbox like "$%FDG%$^GWE43j52409543" and see the difference between new value reflected in textbox and value in the reactive-form!

sample output (image)

This is the directive

@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();
    }
  }
}

Here is the 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
}}

And the form

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);
  }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...