In Angular 5, you can easily prevent interaction with a related button by disabling it when the corresponding reactive

I recently encountered a situation where I needed to implement a reactive form in a component. It looked something like this...

form component.html

<form [formGroup]="form" class="do-form">
    <div formGroupName="dot">
        <div class="do-form__container">
            <div class="do-form__group">
                <label for="day">Day</label>
                <input id="day" type="number" placeholder="XX" class="do-form__group__control" formControlName="day" />
            </div>
            <div class="do-form__group">
                <label for="month">Month</label>
                <input id="month" type="number" placeholder="XX" class="do-form__group__control" formControlName="month" />
            </div>
            <div class="do-form__group">
                <label for="year">Year</label>
                <input id="year" type="number" placeholder="XXXX" class="do-form__group__control" formControlName="year" />
            </div>
        </div>
        <div class="do-form__errors" *ngIf="isValid()">
            <p>Please enter a valid date</p>
        </div>
    </div>
</form>

In the corresponding form.component.ts file

form = this.fb.group({
dot: this.fb.group({
  day: ['',
    [
      Validators.required,
      Validators.min(1),
      Validators.max(31)
    ]],
  month: ['',
    [
      Validators.required,
      Validators.min(1),
      Validators.max(12)
    ]],
  year: ['2018',
    [
      Validators.required,
      Validators.min(1918),
      Validators.max(2018)
    ]]
})
});

isValid() {
return (
  !this.form.valid &&
  this.form.get('dot.day').touched &&
  this.form.get('dot.month').touched &&
  this.form.get('dot.year').touched
);
}

Next, I needed to integrate this form within another page (app.component.html) like this

<app-form #formTool></app-form>
        <button class="full-width-btn" (click)="next(); form.sendResult();">SEND</button>

In the app.component.ts file

import {  formComponent } from '../form-component/form-component.ts'

export ...

@ViewChild(formComponent) form;

My main goal was to disable the send button until the form within the app form component was valid. However, I faced some challenges with this. I considered having a valid event stored on a shared server, but I wasn't sure how to store this in a service. I also explored the option of using ngModel for non-reactive forms, but I wasn't confident if that approach would work in this scenario.

If anyone has any insights or suggestions on how I can achieve this, I would greatly appreciate it!

UPDATE

I've attempted using [disabled]="form.invalid" and [disabled]="!isValid()" but the button remains clickable.

I also tried utilizing [disabled]=!form.isValid() and [disabled]=!form.form.isValid()

Thank you for any assistance provided.

Answer №1

Almost there! Just one more thing to include:

<app-form #formTool></app-form>
<button class="full-width-btn" [disabled]="!isValid()" (click)="next(); form.sendResult();">SEND</button>

Answer №2

To set up an event in a form component, you can create an @Output called formValid and initialize it as a new EventEmitter.

Next, you can watch for changes in the input fields, such as keypress events, and whenever there is a change, verify the validity of the form. If the form is valid, trigger the event by calling formValid.emit().

In the main app component, set formIsValid to false initially. Within the app-form element, you can listen for the formValid event using: < app-form (formValid)="formIsValid = true"> (or by calling a function in app.component.ts rather than using inline code).

Lastly, on the button element, you can disable it until the form is valid by using: < button [disabled]="!formIsValid">

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

Learn how to showcase real-time stock information from Yahoo Finance on an Android device. See the JSON format provided below for guidance

finance_charts_json_callback( { "meta" : { "uri" :"/instrument/1.0/PTC/chartdata;type=quote;range=1d/json/", "ticker" : "ptc", "Company-Name" : "PTC Inc.", "Exchange-Name" : "NMS", "unit" : "MIN", "timezone" : "EDT", "curr ...

What is the best way to show a tooltip alongside highlighted text?

How can I display a tooltip (using qTip) next to selected text? The code below captures the selected text in the console, but the tooltip is not displayed. <div class='test'>Actual text will be much longer...Test Test Test Test Test Test T ...

Redux export does not complete correctly unless brackets are used

I'm trying to understand why the main JS file is having trouble importing todo from './actions' without brackets, while there are no issues with importing todos from './reducers'. Main js-file: import { createStore } from 'r ...

Using javascript within a PHP file

I'm struggling to implement this JavaScript function within a PHP page (footer.php), but it's not functioning as expected. I've experimented with various approaches, even attempting to include the script within a PHP echo statement, but that ...

When uploaded to Amazon CloudFront, web application routes fail to function properly

I am facing an issue with my Next.js single page app that utilizes static paths. When running it locally or exposing it directly from an AWS S3 distribution, everything works fine. However, once served via AWS CloudFront, accessing paths other than the roo ...

Refreshing a page in Angular 4/5 using TypeScript

I am currently working on a single-page application that utilizes routes for navigation: this.router.navigate(['/customer-home'], { skipLocationChange: true }); While on the customer home page, I have a feature to add a new customer via a REST ...

Iterate over the array and eliminate any stylesheets

Currently working on a website using WordPress, and dealing with some unwanted css files that come with certain plugins. I've been attempting to remove these stylesheets with JavaScript but keep running into an error saying Failed to execute 'qu ...

Is the Browser not Opening when Running npm start with webpack Due to a Peer Dependency Issue with [email protected] and webpack@^4.0.0?

I just started learning JavaScript and decided to explore the webpack-starter project on GitHub (https://github.com/wbkd/webpack-starter). Following the instructions, I cloned the repository and ran npm install in the project folder. Upon encountering a lo ...

How can I create an input field that only reveals something when a specific code is entered?

I am currently developing a website using HTML, and I would like to create an admin section that requires a password input in order to access. After consulting resources on w3schools, I attempted the following code: <button onclick="checkPassword()" i ...

Error: An unidentified type was encountered that is not a functioning element within an anonymous PHP JavaScript function

Hello everyone, I am seeking help with a JavaScript error that is causing some trouble. Whenever I try to sort a table and implement pagination in PHP, I get an error message in the console stating "Uncaught TypeError: undefined is not a function." Despite ...

Utilizing Filestack in Angular 2

I'm currently working on integrating image uploading functionality into my Angular 2 App, and I have decided to utilize Filestack (formerly filepicker.io) for storing the images. Following Filestack's recommendations, I added the necessary script ...

Getting an error message of 'Unable to locate Firebase Storage Default Bucket on the server?

I'm currently facing an issue with the server not being able to locate the bucket. To troubleshoot, I've stored the token and other crucial details in a separate file as a string. Afterwards, I split it and utilize the relevant text in my Javascr ...

How can we incorporate a Material-UI skeleton to display API response data effectively?

I have incorporated the material-ui skeleton (Shimmer effect) to display data fetched from an API. { accountData.usersAccountData.map((userData, index) => ( // ...UI code ) ) } The output is shown below : https://i.sstatic.net/MEVhA.png It can be o ...

Saving JSON data into an array in Angular with TypeScript can be accomplished by creating

Currently, I am encountering an issue while utilizing the Angular mention library. Below is the typescript code I am working with: items: Object[] = ["jay","roy","gini","rock","joy","kiya"]; I am utilizing the array named items in my component.html file ...

A guide to replicating HTML using AngularJS

I am attempting to replicate HTML content using AngularJS. While I was successful using jQuery, it caused conflicts with Angular. Therefore, I aim to achieve the same result using AngularJS. Here is the code I have written: function printContent(el){ ...

Dynamic JSX tag including attributes

In my project, I have a set of components stored in a folder named systemStatus. These components are accessible through an index.js file as follows: export UserCount from './UserCount' Additionally, I have a JSX component called Status which i ...

Struggling with updating a user in MongoDB using findOneAndUpdate and encountering a frustrating internal server error 500?

Presently, I am in the process of developing an API that is designed to update the current user in mongoDB based on the data provided in the request. However, whenever I execute findOneAndUpdate(), I encounter a 500 internal server error. (I will outline ...

Prevent unnecessary requests for asset images in Angular 5

Within my Angular application (running version 5.1.0, built with angular-cli and webpack), I have a country selector component that allows users to choose a country from a drop-down menu or by typing the name in an autocomplete field. Each matching result ...

Node.js encountering unexpected pattern during RegExp match

Currently, I'm developing a script that aims to simplify local testing by creating a Node server for all my Lambda functions. My main challenge lies in extracting all the dbconfig objects from each file. To test out various patterns, I rely on . Surpr ...

What distinguishes injecting a provider in Angular2's @Component versus @Module?

When working with Angular2, it is possible to specify the providers in either a @Component element or in a @NgModule element. For example: @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: [&apos ...