首页 > 解决方案 > 基于输入更改的角度启用和禁用组件或元素

问题描述

我们如何在 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]],
    });
  }

标签: javascriptangulartypescript

解决方案


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>

推荐阅读