stopPropagation()可以防止在表单无效时触发回调doSearch()
。
<form
[dirtyFieldsOnSubmit]="form"
(ngSubmit)="doSearch()"
#form="ngForm"></form>
指令代码:
import {Directive, Input, HostListener} from '@angular/core';
import {NgForm} from '@angular/forms';
@Directive({ selector: '[dirtyFieldsOnSubmit]' })
export class DirtyFieldsOnSubmitDirective {
@Input('dirtyFieldsOnSubmit') form: NgForm;
constructor() {
}
@HostListener('submit', ['$event'])
onSubmit(event) {
if(!this.form.valid) {
for (var i in this.form.controls) {
this.form.controls[i].markAsDirty();
}
//event.stopPropagation() not working
}
}
constructor() {
}
}
答案 0 :(得分:0)
只需在功能结束时添加return false
即可。这会阻止传播。