[英]Interaction with a matSuffix mat-checkbox in a mat-form-field
[英]Unexpected behaviour from mat-form-field matInput, matSuffix, and reactive form
我試圖弄清楚為什么在切換密碼輸入的可見性圖標時提交表單。
來自 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>
這是頁面加載時模板顯示的內容:
默認情況下,表單內的按鈕會考慮type="submit"
。
所以你必須把它做成普通的按鈕,比如..
<button type="button" mat-icon-button matSuffix (click)="hide = !hide">
<mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
</button>
在這里我添加了type='button'
希望這會幫助你讓我知道如果有問題..
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.