Ishaan Jaya
Ishaan Jaya

Reputation: 1

Angular enabling and disabling component or element based on input changes

How do we do this in angular, make button disabled by default if email address is invalid , If email is invalid get started button will enable and the user can click get started button ,

after the user click get started button it will disabled again and will only enable again if user changes the email input and if the new email input is valid , vice versa.

I already have the checked and the form controls , but is there a cleaner way to do this in angular? Thanks.

#html code

 <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 validation code

 ngOnInit(): void {
    this.initFormGroup();
  }

  initFormGroup() {
    this.modelForm = this.formBuilder.group({
      id: [this.model.id || 0],
      emailAddress:[this.model.emailAddress,[Validators.required, Validators.email]],
    });
  }

Upvotes: 0

Views: 1841

Answers (1)

Peter Bucher
Peter Bucher

Reputation: 48

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>

Upvotes: 1

Related Questions