Angular项目中[disabled]属性失效:提交按钮未按预期禁用
问题描述
我在Angular项目中开发了一个登录页面,为提交按钮设置了[disabled]="!loginForm.valid"绑定,期望只有当输入框填入有效内容后按钮才可用,但运行时按钮并未被禁用,已在Component.ts中完成表单关联,请问为何该属性未生效?
相关代码如下:
HTML模板
<div class="container"> <form [formGroup]="loginForm" (submit)="onSubmit()"> <p> <label for="username">User Name:</label><br> <input type="text" name="username" id="username" formControlName="userName"><br> <span class="text-danger" *ngIf="!loginForm.controls.userName.valid && loginForm.controls.userName.dirty"> invalied username! </span> </p> <p><label for="password">Password:</label><br> <input type="text" name="password" id="password" formControlName="passWord"><br> </p> <button type="submit" class="btn btn-success" [disabled]="!loginForm.valid">Enter</button> </form> </div>
Component代码
import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-log-in', templateUrl: './log-in.component.html', styleUrls: ['./log-in.component.css'] }) export class LogInComponent { loginForm=new FormGroup({ userName: new FormControl(' ',[Validators.required]), passWord: new FormControl(' ',[Validators.required]), }) onSubmit() { console.log(this.loginForm.value); } }
问题原因
Validators.required 验证器仅会判定**null、undefined、空字符串('')为无效值,你初始化表单控件时传入的是空格字符(' ')**,不属于上述无效范畴,因此userName和passWord控件始终会被判定为有效,整个loginForm的valid状态一直是true,导致按钮的disabled绑定结果永远为false,按钮不会被禁用。
解决方案
有三种常用修复方式,可根据需求选择:
将控件初始值改为空字符串
把FormControl的初始值从' '替换为'',让Validators.required能正常触发验证:loginForm=new FormGroup({ userName: new FormControl('',[Validators.required]), passWord: new FormControl('',[Validators.required]), })添加最小长度验证
给控件加上Validators.minLength(1),即使初始值是空格,也会要求输入至少1个有效字符:loginForm=new FormGroup({ userName: new FormControl(' ',[Validators.required, Validators.minLength(1)]), passWord: new FormControl(' ',[Validators.required, Validators.minLength(1)]), })自定义去除空格验证器
如果需要禁止纯空格输入,可以自定义验证器检查去除空格后的内容是否为空:import { AbstractControl, ValidatorFn } from '@angular/forms'; export function noWhitespaceValidator(): ValidatorFn { return (control: AbstractControl): {[key: string]: any} | null => { const isWhitespace = (control.value || '').trim().length === 0; return isWhitespace ? { 'whitespace': true } : null; }; } // 组件内使用 loginForm=new FormGroup({ userName: new FormControl(' ',[Validators.required, noWhitespaceValidator()]), passWord: new FormControl(' ',[Validators.required, noWhitespaceValidator()]), })
内容的提问来源于stack exchange,提问作者Kavi Vignesh
相关产品推荐
相关产品推荐

