Controlling the visibility of components or elements in Angular through input modifications

Is there a more efficient way to handle button disabling and enabling based on email validation in Angular? I already have form controls set up, but want to make the process cleaner. The goal is to disable the "Get Started" button by default if the email address is invalid. Once the user enters a valid email, the button should enable for them to click. However, after clicking the button, it should be disabled again until the user changes the email input to a valid one. Any suggestions would be appreciated. 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 an 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]],
    });
}

Answer №1

Angular comes equipped with its own set of validators that you can utilize, especially when paired with the ReactiveFormsModule module that needs to be imported in your app.module.ts file.

In your TypeScript file, you can implement it as follows:

 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])
   });
}

Then, in your HTML file, you can check the validity of these form controls.

<form [formGroup]="formGroup">
  <input type="text" formControlName="email">
  <button type="button" [disable]="form?.get('emailAddress').invalid">
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining individual TypeScript files together

Recently, I encountered an issue with 2 typescript files: a.ts: let some : string = "some"; b.ts: console.log(some); Surprisingly, when compiling both files together by including them in the tsconfig or command line, there was no error about 'som ...

How can I slow down the response time in Express Node?

I have set up a route that triggers an asynchronous function when the URL is accessed. This function will eventually return a value, which I want to use as the response for the get request. However, I am facing an issue with delaying the response until the ...

Using jQuery Ajax to Send Values Between Functions and Replace Nulls

I need assistance with handling the value from a dropdownlist in my JavaScript function. The function works well if the value is not Null, but I want to replace a Null value with the static value "asc" before passing it to the next function. function g ...

The appropriate method for transferring a prototype to an object

From my perspective, prototypes work like this: let Animal = function() { this.bark = "woof"; } Animal.prototype.barkLoud = function() { return this.bark.toUpperCase(); } let x = new Animal(); x.barkLoud() = "WOOF"; I f ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

The Express app.post endpoint is not acknowledging incoming POST requests from Postman

I am facing an issue where my POST request using Postman to my express app is timing out. Here is the request: https://i.sstatic.net/UfL07.png And here is the app: import express from 'express' import bodyParser from 'body-parser' i ...

What is the best way to show the previous month along with the year?

I need help with manipulating a date in my code. I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and want to output Oct. 2020. However, when I wrote a function to achieve this, I encountered an error message: ERROR TypeError: fiscalYear ...

Optimizing Angular Performance with Trackby in Dual Lists

How can I write two ngFor lists with trackby to prevent elements from being recreated when moving between the lists? I know that trackby helps in avoiding recreation of elements within a single list, but is there a way to achieve this across multiple list ...

Angular constantly looping due to $watchCollection being triggered repeatedly

I am interested in monitoring the changes of an object, referred to as x, specifically its properties which are checkboxes. When a user checks a box, it alters the checked property (prop1) to 1. Each property contains certain content, and when enabled, it ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

Unable to update div CSS using button click functionality

I have been working on this HTML/CSS code and I am trying to change the style of a div using a JavaScript button click event so that the div becomes visible and clickable. However, despite my efforts, it doesn't seem to be working as expected. Whenev ...

steps for including a JS file into Next.js pages

Is it possible to directly import the bootstrap.bundle.js file from the node_modules/bootstrap directory? import "bootstrap/dist/css/bootstrap.rtl.min.css"; function MyApp({ Component, pageProps }) { return ( <> <Script src="node_m ...

Having trouble including a YouTube iframe code within the document ready function

I am having trouble getting the youtube iframe API code to work properly within my $(document).ready() function. When I try to add the code inside the function, the player does not load. However, when I move the code outside of the document.ready, the play ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require(&apo ...

Implementing try-catch logic for element visibility in Playwright using TypeScript poses limitations

There is a specific scenario I need to automate where if the title of a page is "Sample title", then I must mark the test as successful. Otherwise, if that condition is not met, I have to interact with another element on the page and verify if the title ch ...

The 'filter' attribute is not found in the 'ContextProps' type

I am currently working on a project in Next.js 13 where I am trying to render card items conditionally based on their status. The TypeScript version being used is "5.2.2". However, I encountered an error that says: Property 'filter' does not exis ...

encountered difficulties while attempting to install npm i due to node-gyp errors

When attempting to run npm i --force, I encounter the following error: pm ERR! code 1 npm ERR! path /Users/moblizeit/GitHub/code-repo/apps/business-card-scanner/admin/businesscardadmin/node_modules/grpc npm ERR! command failed npm ERR! command sh -c -- nod ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

Switch out the words within the input box

My code has the ability to convert words to numbers, however, when I try to paste a text like: three four one one four five six one, the output I receive is: 3411456one If I click on the text input again, the word 'one' changes to '1', ...

Unable to access remote video streams by directly modifying URL parameters

Recently, I delved into experimenting with the straightforward mediasoup demo available at: https://github.com/Dirvann/mediasoup-sfu-webrtc-video-rooms After setting up the demo, everything seemed to be functioning correctly. The initial task on my agend ...