【问题标题】:How to add buttons without submit the form in Angular?如何在不提交 Angular 表单的情况下添加按钮?
【发布时间】:2019-09-05 04:42:00
【问题描述】:

在 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>

【问题讨论】:

  • 只需添加type='button'即可。

标签: angular angular-forms


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    去掉form标签中的(ngSubmit)="submit()",放到按钮中,如下所示:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        只需添加type='button' 即可。表单中未定义任何type 的按钮的作用类似于表单的submit 按钮。

        【讨论】:

          【解决方案5】:

          共有三种按钮:

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

          所以你只需要将类型属性更新为按钮

          模板

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

          resources

          【讨论】:

            【解决方案6】:

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

            @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');
               }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-20
              • 2016-08-29
              • 1970-01-01
              • 1970-01-01
              • 2011-12-04
              相关资源
              最近更新 更多