Activate submit button when checkbox is chosen in Angular 5

When the checkbox is selected, I want to enable the submit button. This functionality is being implemented in Angular 5 with TypeScript. Below is my current code:

<mat-checkbox>I agree to Terms & Conditions</mat-checkbox>
<button mat-button class="NxtBtnWrap" type="submit">Submit</button>

Answer №1

To determine if you can enable or not, you can utilize the change event as shown below:

TS file:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  disabledAgreement: boolean = true;
  changeCheck(event){
    this.disabledAgreement = !event.checked;
  }
}

Template:

<mat-checkbox (change)="changeCheck($event)">I agree to Terms & Conditions</mat-checkbox>
<button [disabled]="disabledAgreement" mat-button class="NxtBtnWrap" type="submit">Submit</button>

For further details, click here

Alternatively, you can use ngModel:

TS file:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  checked: boolean = false;
}

Template:

<mat-checkbox [(ngModel)]="checked">I agree to Terms & Conditions</mat-checkbox>
<button [disabled]="!checked" mat-button class="NxtBtnWrap" type="submit">Submit</button>

Don't forget to import the FormsModule module in your app.module.ts to use ngModel:

import { FormsModule } from '@angular/forms';

and add it to the imports array:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MatCheckboxModule,
    MatButtonModule,
    FormsModule,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №2

According to the response provided by @SergioEscudero, a modification needs to be made in the following method:

changeCheck(event){
    this.disabledAgreement = !event.checked;
  }

In order for it to function properly, the code should be adjusted to:

changeCheck(event){
    this.disabledAgreement = !event.target.checked;
  }

Answer №3

To simplify things, ensure that your TypeScript file includes a FormGroup for interaction:

ngOnInit() {
  this.dialogFormGroup = formBuilder.group( {
    confirmAction: [false]
  } );
}

Next, connect the checkbox to the FormControl, and set up the button's disabled property based on the checkbox value:

<form  [formGroup]="dialogFormGroup">
  <mat-checkbox formControlName="confirmAction">I agreeTerms & Conditions</mat-checkbox>
  <button mat-button class="NxtBtnWrap" type="submit" [disabled]="!dialogFormGroup.controls.confirmAction.value">Submit</button>
</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

The server sent events are not being received by the front end

I am currently attempting to subscribe to events on BE using an EventSource on the FrontEnd of my application. The issue appears to be with the event listener, as I am able to reach the BE endpoint and register the subscriber. On the FrontEnd, I am utiliz ...

Having difficulty placing markers on a Mapbox map using mapbox-gl.js

I've been working tirelessly to incorporate markers onto a mapbox map using mapbox-gl-js with typescript. Despite following various tutorials from the mapbox site, I haven't been able to get it to work. mapboxgl.accessToken = 'mykey&apo ...

Retrieve the data stored within an [Object Promise] for further use

Having trouble utilizing a value retrieved from an API call. Below is my TypeScript code: private async fetchPersonName() { let fullName = await Api.getName('Data($select=FullName)', `personId eq ${currentPersonId}`); ...

Filtering an array in Angular, but excluding the initial element from the filter process

I am currently dealing with an array of objects that I need to filter. My issue is that I do not want the first element in the array to be removed during the filtering process. Here is an example of how the array (oData) might be structured: [ {id: " ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...

Using Angular 2, invoke a function within an API call

I have been attempting to incorporate a function within an API call. Despite implementing the following logic thus far, it is not functioning as intended. code changeStatus(id) { this.http.post('https://localhost:44300/api/apis/ChangeStatus/' ...

In my TS file, I am aiming to retrieve an element using ViewChild in Angular version 15

Every time I attempt to log a ViewChild element in either the ngAfterViewInit() or ngOnInit() functions, it always logs undefined in the console. This is how my HTML file looks: <input type="number" #phoneNumber> And here is my TypeScript ...

Managing Array Construction through Checkbox Toggle in Angular 2 Application

Trying to create a simple toggle function in my Angular 2 app where selections made via checkboxes build an array. I recall a method where toggling can be achieved by setting one function equal to its opposite. Here are the functions for adding and removin ...

Saving asynchronous data in Ionic 3: The ultimate guide

I'm working on a news app where I retrieve data from my Json API using the Http Client. I want to ensure that my data remains stored even if there is no internet connection or if the user closes/restarts the app. Currently, I retrieve my data in an o ...

Handling Mongoose Schemas and Database Conflicts in TypeScript

As a newcomer to MongoDB and Mongoose, I am facing a dilemma when it comes to sorting out conflicts between the schema and the database. Specifically, if I have an existing database in place and then decide to update the schema in my project by adding de ...

Issue Encountered during 'ng build --prod' Command: Prompt requesting addition of '@Pipe/@Directive/@Component annotation'

Encountered an error while running ng build --prod on my MEAN Stack App. The error message reads : ERROR in : Unexpected module 'FlashMessageModule in C:/mean/angular/node_modules/angular-flash-message/dist/flash-message.module.d.ts' declared ...

PIXI.js fails to optimize image loading and loads the same image multiple times when a base URL is used

I'm in the process of developing a game using PIXI.js that will be accessed through URL X but loaded on another website at URL Y. To make this possible, I've implemented an environment variable called BASE_URL. This variable is set to '&apo ...

A guide to leveraging TypeScript generics for accurate validation of object values

In a unique scenario, I am tasked with creating an object configuration for predefined filters using TypeScript generics. Here is the current configuration: const filterOptions: FilterOption[] = [ // Valid filters { field: 'name', operator: ...

Subclass method overloading in Typescript

Take a look at this example: class A { method(): void {} } class B extends A { method(a: number, b: string): void {} } An error occurs when trying to implement method() in class B. My goal is to achieve the following functionality: var b: B; b.met ...

"Caution: The `className` property did not align" when configuring a theme provider within Next.js

I'm currently working on developing a theme provider using the Context API to manage the application's theme, which is applied as a className on the body element. The implementation of the context is quite straightforward. When initializing the ...

Is there a method in Typescript and React Native to save the state of a switch button?

Is there a way to save the switch button state using asyncstorage? I want to ensure that when the user toggles the switch, the state is saved even if they exit the application and come back. import { View, Text, Switch } from 'react-native'; impo ...

Tips for bundling TypeScript Angular with internal modules using SystemJS

We have been exploring the idea of transitioning some of our angular projects to typescript, but we are encountering difficulties with internal modules/namespaces. For reference, we have shared a working example on github: https://github.com/hikirsch/Typ ...

Using Angular's [ngIf], [ngIfElse], and [ngIfElseIf] functionalities enables dynamic content rendering

Currently, I have the following code snippet: <ng-container *ngIf="someCondition"> <ng-template [ngIf]="cd.typedType === 'first'" [ngIfElse]="Second"> <div class="row"> fir ...

Steps to resolve the 'form' variable being assigned a value but never used in axios:

I am encountering an issue with a contact form that utilizes React with axios on the frontend and Express with nodemailer on the backend while running locally. The expected outcome is for me to receive an email when I click the "Submit" button. However, up ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...