Angular 如何在不提交表单的情况下添加按钮?

How to add buttons without submit the form in Angular?

在Angular中,如何在不提交表单的情况下添加按钮?

例如我想在不提交表单的情况下调用 onCancel,但是更新按钮应该是提交表单,并且仍然保留 ngSubmit.

<form [formGroup]="form" (ngSubmit)="submit()">
    <p>
    <select ...>...</select>
    </p>
    <p>
    <button
        type="submit"
        mat-raised-button
        color="primary">
        update
    </button>
    <button mat-raised-button (click)="onCancel($event)">
        cancel
    </button>
    </p>
</form>

您可以将$event.preventDefault()添加到按钮点击事件

<button mat-raised-button (click)="onCancel($event); $event.preventDefault()">

删除表单标签中的 (ngSubmit)="submit()" 并将其放入按钮中,如下所示:

<button
    (click)="submit()"
    mat-raised-button
    color="primary">
    update
</button>

您可以使用 type="button",如果您没有提及任何类型,则默认情况下该按钮被视为提交类型。所以对于非提交按钮,你的代码应该看起来像这样。

<button type="button" mat-raised-button (click)="onCancel($event)">
        cancel
</button>

只需添加 type='button' 即可。表单中没有任何定义 type 的按钮就像表单的 submit 按钮一样。

按钮分为三种类型:

  • submit : 提交当前表单数据。 (This is default.)
  • reset : 重新设置当前表单中的数据。
  • 按钮:只是一个按钮。它的作用 必须由其他东西控制(即 JavaScript)。

所以你只需要将type属性更新为button

模板

<button type="button" mat-raised-button (click)="onCancel($event)">
    cancel
</button>

resources

总的来说,我不喜欢默认按钮类型是提交的想法,我创建了以下指令来使事情正确,没有类型设置的按钮明确默认为按钮:

@Directive(
{
   selector: 'button:not([type])'
})
export class ButtonTypeDirective implements OnInit
{
   constructor(private el: ElementRef<HTMLButtonElement>, private renderer: Renderer2) 
   {
   }

   public ngOnInit()
   {
       this.renderer.setAttribute(this.el.nativeElement, 'type', 'button');
   }
}