【发布时间】:2021-04-27 13:47:22
【问题描述】:
我在使用响应式表单中的指令粘贴文本输入时遇到问题。
您可以在 https://stackblitz.com/edit/angular-klzz2y 看到该问题。在该文本框中输入一些内容,例如“$%FDG%$^GWE43j52409543”,然后查看文本框中反映的新值与反应形式中的值之间的区别!
这是指令
@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