Angular 2允许指令同时执行和操作

时间:2017-05-15 14:44:24

标签: angular typescript

我有一个指令阻止双击提交按钮:

import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core';

@Directive({
  selector: 'button[type=submit]'
})
export class PreventDoubleSubmit {

  @HostBinding() disabled:boolean = false;

  @Input() valid:boolean = true;      

  @HostListener('click') 
  onClick() {
      console.log("aaa");
    this.disabled = true;
  }
}

然后我在共享模块中使用它:

import { NgModule } from '@angular/core';
import { PreventDoubleSubmit } from '../shared/prevent-double-submit.directive';

@NgModule({
    declarations: [
        PreventDoubleSubmit
    ],
    exports: [
        PreventDoubleSubmit
    ]
})
export class SharedModule{}

然后在app.module中使用它。应用程序中的任何表单现在都可以在第一次单击时正确禁用该按钮。然而,表格中的原始行为现在根本不起作用。它似乎指令已经完全优先于所有事情,并防止发生任何其他事情。

我使用以下表单标记:

<form (ngSubmit)="onSubmit(f)" #f="ngForm" class="generalForm"></form>

然后在我使用的打字稿中:

onSubmit(form: NgForm) {
        console.log("This is the code I want to perform");
}

1 个答案:

答案 0 :(得分:0)

我使用你的指令进行了小改动

import { Directive, HostListener, Input, HostBinding } from '@angular/core';

@Directive({
    selector: 'button[name=saveButton]'
})
export class PreventDoubleSubmit {

    @HostBinding() disabled: boolean = false;

    @Input() valid: boolean = true;

    @HostListener('click')
    onClick() {
        console.log("saveButton is disabled");
        this.disabled = true;
    }
}

然后我在app.module

中导入了它
@NgModule({
    imports:[...],
    declarations: [
...
PreventDoubleSubmit,
...
]
export class AppModule { }

和我一起工作。

相关问题