Angular mat form字段matInput、matSuffix和reactive form的意外行为

Angular mat form字段matInput、matSuffix和reactive form的意外行为,angular,angular-material,angular-reactive-forms,ng-submit,Angular,Angular Material,Angular Reactive Forms,Ng Submit,我试图找出在切换密码输入的可见性图标时提交表单的原因 从login.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['

我试图找出在切换密码输入的可见性图标时提交表单的原因

从login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  public loginForm: FormGroup;
  public hide: boolean = true;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.loginForm = this.fb.group({
      email: [""],
      password: [""]
    })
  }

  onSubmit() {
    console.log("Form submit event fired...");
    console.log(this.loginForm.value);
  }

}

发件人:login.component.html

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
        <mat-card>
            <mat-card-header>
                <mat-card-title>
                    Login
                </mat-card-title>
            </mat-card-header>
            <mat-card-content>
                <div fxLayout="column">
                    <mat-form-field appearance="outline">
                        <mat-label>Email</mat-label>
                        <input matInput placeholder="Placeholder" formControlName="email">
                    </mat-form-field>
                    <mat-form-field appearance="outline">
                        <mat-label>Password</mat-label>
                        <input matInput [type]="hide ? 'password' : 'text'" formControlName="password">
                        <button mat-icon-button matSuffix (click)="hide = !hide">
                        <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
                        </button>
                    </mat-form-field>
                </div>
            </mat-card-content>
            <mat-card-actions>
                <button mat-button (click)="onSubmit()">Login</button>
            </mat-card-actions>

        </mat-card>
    </form>

登录
电子邮件
密码
{{隐藏?'visibility_off':'visibility'}
登录
这是页面加载时模板显示的内容:

然后我点击输入框上的图标,它会工作,并将输入类型从“密码”切换到“文本”。

但是,如果我再次单击图标,将输入类型切换回“password”,似乎会触发onSubmit()方法:

表单内的按钮,默认情况下会考虑<代码>类型=“提交”< /代码>。 所以你必须把它做成一个简单的按钮

 <button type="button" mat-icon-button matSuffix (click)="hide = !hide">
                        <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
                        </button>

{{隐藏?'visibility_off':'visibility'}
这里我添加了
type='button'

希望这将有助于你让我知道如果有问题


谢谢

hi@n如果您还有问题,请告诉我?