javascript - 基于输入更改的角度启用和禁用组件或元素
问题描述
我们如何在 Angular 中执行此操作,如果电子邮件地址无效,则默认禁用按钮,如果电子邮件无效,则将启用开始按钮,用户可以单击开始按钮,
用户单击开始按钮后,它将再次禁用,并且只有在用户更改电子邮件输入并且新的电子邮件输入有效时才会再次启用,反之亦然。
我已经有检查和表单控件,但是有没有更简洁的方法来做这个?谢谢。
#html代码
<mat-form-field class="full-width" appearance="fill" style="margin-top: 20px;">
<mat-label>Email</mat-label>
<input type="email" matInput autocomplete="emailAddress" matInput formControlName="emailAddress" />
<mat-error *ngIf="modelForm.get('emailAddress').hasError('email')">
Email is in invalid format.
</mat-error>
<mat-error *ngIf="modelForm.get('emailAddress').hasError('required')">
Email is required.
</mat-error>
</mat-form-field>
</div>
<div style="text-align:right;margin-top: 19.0px;">
<button click)="getStarted()" [disabled]="!modelForm.get('emailAddress')?.valid" mat-flat-button color="primary"
class="v-btn-sml" id="get-started-button">
Get Started
</button>
</div>
#ts 验证码
ngOnInit(): void {
this.initFormGroup();
}
initFormGroup() {
this.modelForm = this.formBuilder.group({
id: [this.model.id || 0],
emailAddress:[this.model.emailAddress,[Validators.required, Validators.email]],
});
}
解决方案
Angular has built in validators you can use, combining it with the ReactiveFormsModule you have to import in your app.module.ts.
In your typescript file you can do it like:
formGroup: FormGroup;
private model: { id: number; emailAddress: string } = {
id: 1,
emailAddress: ''
};
ngOnInit() {
this.formGroup = new FormGroup({
id: new FormControl(this.model.id),
email: new FormControl(this.model.emailAddress, [Validators.email])
});
}
And than in your html file you can access this formControls valid/invalid state.
<form [formGroup]="formGroup">
<input type="text" formControlName="email">
<button type="button" [disable]="form?.get('emailAddress').invalid">
</form>
推荐阅读
- mysql - MySql - concat 表达式不断附加相同的值
- memory-leaks - CListCtrl 项目计数限制和内存 (RAM) 使用
- apache-kafka - Confluent Kafka S3 sink 连接器在使用 Parquet 格式时抛出`java.lang.NoClassDefFoundError: com/google/common/base/Preconditions`
- regex - Azure 应用程序网关自定义标头规则
- mongodb - MongoDB 查询以查找具有共同值的字段并返回这些字段的所有详细信息
- selenium - 通过 docker-compose 在 selenium 网格上设置不同的 chrome 版本
- android - 如何将此 JSON 格式转换为模型类并使用改造将响应转换为列表
- spring-security - Spring Security 5 - 如何使用对称签名密钥?
- jar - 如何找到 Gradle 依赖项的 jar
- ios - 使 iOS 应用程序仅适用于具有 LIDAR 的设备?