Angular 2无法阻止ngSubmit传播

时间:2016-11-01 03:24:28

标签: angular

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() {
  }
}

1 个答案:

答案 0 :(得分:0)

只需在功能结束时添加return false即可。这会阻止传播。