Turn off the button and add a CSS class to it when sending a message

I have an Angular 7 component with a form that includes the following TypeScript code:

export class MessageComponent implements OnInit { 

  message: FormGroup;

  constructor(private formBuilder: FormBuilder, private messageService: MessageService) { }

  ngOnInit() {

    this.message = this.formBuilder.group({ 
      content: ['']
    });

  }

  onSubmit() {

    if (this.message.valid) {

      let request: SendMessageRequest = { 
        content: this.message.value.content
      };

      this.messageService.send(request).subscribe(
        (response: SendMessageResponse) => { 
          this.message.reset();
        },
        (error) => {
          // Handle errors           
        }
      );

    }
  }
}

The corresponding HTML form looks like this:

<form [formGroup]="message" (ngSubmit)="onSubmit()">
  <label for="content">Content</label>
  <textarea id="message" formControlName="content"></textarea>
  <button class="action" type="submit">Send Message</button>
</form>

Is there a way to disable the button while the message is being sent by the service?

Also, how can I add a specific CSS class to the disabled button?

Answer №1

To dynamically add a class conditionally (using ngClass) to a button and either display a spinner or disable it, you can set the CSS class for disabled and also set the button attribute to disabled.

For example:

<button class="action" type="submit" [ngClass]="{'disabled': sendDisabled}" [disabled]="sendDisabled">Send Message</button>

In your component TypeScript file:

onSubmit() {

        if (this.message.valid) {
            let request: SendMessageRequest = {
                content: this.message.value.content
            };
            this.sendDisabled = true; // Disable button while sending message
            this.messageService.send(request).subscribe(
                (response: SendMessageResponse) => {
                    this.message.reset();
                    this.sendDisabled = false; // Enable button after receiving response
                },
                (error) => {
                    // Handle errors here          
                }
            );

        }
    }

Don't forget to define sendDisabled in your component TypeScript file. Also, add styles for the disabled class in your CSS:

button.disabled{
  pointer-events: none;
}

Answer №2

To create a condition using ng-class, follow the example below:

<button [class.action]="myCondition" type="submit">Send Message</button>

TypeScript Code:

myCondition: boolean = false;
disableButton: boolean= false;

constructor(private formBuilder: FormBuilder, private messageService: MessageService) { }

ngOnInit() {
  this.message = this.formBuilder.group({ 
    content: ['']
  });
}

onSubmit() {
 if (this.message.valid) {

  let request: SendMessageRequest = { 
    content: this.message.value.content
  };
  this.myCondition= true; //showClass
  this.messageService.send(request).subscribe(
  this.disableButton = true;
    (response: SendMessageResponse) => { 
      this.message.reset();
    },
    (error) => {
      // Handle errors here           
    }
   );
  }
 }
}

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

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Eliminate unnecessary spacing from the sticky container

Trying to implement a sticky menu in an angular 14 project using angular material 14 has been quite challenging for me. Initially, I attempted to use the 'fixed' position, but encountered issues where the menu would consistently return to the to ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Utilize Primeng data grid to calculate total sum and display it in the footer section

I have been utilizing primeng datatable in a recent project and am currently facing an issue with calculating the sum in the footer of a row grouping DataTable. The summation needs to occur while data is being edited and new data is being entered. Below i ...

Type errors in NextJS are not being displayed when running `npm run dev`

When encountering a typescript error, I notice that it is visible in my editor, but not in the browser or the terminal running npm run dev. However, the error does show up when I run npm run build. Is there a method to display type errors during npm run d ...

Determine the value added tax in your online shopping basket

Currently, I am in the process of developing a webshop for a pizzeria using Angular, and recently completed work on my cart component. One of the key features I wanted to incorporate was adding a 10% Value-Added Tax (VAT) for each item in the cart and incl ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Is it possible for me to download npm locally using the command line? I am looking to install an older version of npm for a project that requires it

I currently have two Angular projects on my computer: The first project is built in Angular 14 and connected to Java. The installations of npm and ng are carried out using Maven plugins. Here is an example of the Maven plugins being called with configurat ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Material-UI chart displays only loading lines upon hovering

Currently, I am utilizing a Material UI Line chart in my NextJS 14 application to showcase some data. Although the data is being displayed properly, I have encountered an issue where the lines on the chart only render when hovered over, rather than appeari ...

Pressing the enter key on a table column in Angular will trigger an automatic button click

In my Angular 9 application, I have a dynamic table in the HTML with editable columns. When I edit a value and press ENTER, it triggers a click event associated with a button in another column instead of applying the edit. How can I prevent this unexpected ...

The property you are trying to access is not found within the declared type of 'IntrinsicAttributes & { children?: ReactNode; }'

In my React project created using Create-React-App, I have included the following packages (relevant to the issue at hand): "react": "^16.13.1", "react-dom": "^16.13.1", "react-router-dom": "^5.1.2", "react-scripts": "3.4.1", "typescript": "^3.9.2", "@typ ...

Tips for stopping the navigator from adding content to an HTML input in an Angular application

I am facing an issue with two input fields in my Angular project. These fields are supposed to take values automatically from the browser, and I have tried using the HTML autocomplete option without success. Here is a snippet of my HTML code: <div clas ...

Mastering Two-Way Binding in Angular 2 with JavaScript Date Objects

I am currently utilizing Angular 2 and have encountered the following code: Within the JS file, this code initializes the employee-variable for the template: handleEmployee(employee : Employee){ this.employee = employee; this.employee.sta ...

Issue encountered during the creation process of a new component within Angular 4

While attempting to create a new component named signup-form using the command: ng generate component signup-form / ng g component signup-form An error is being thrown that reads: Unexpected token / in JSON at position 1154 The source of this error i ...

What is the error message "Cannot assign type 'IArguments' to argument"?

Currently employing a workaround that is unfortunately necessary. I have to suppress specific console errors that are essentially harmless. export const removeConsoleErrors = () => { const cloneConsoleError = console.error; const suppressedWarnings ...

Using Typescript with Angular 2 to Implement Google Sign-In on Websites

Currently, I am in the process of creating a website that utilizes a typical RESTful web service to manage persistence and intricate business logic. To consume this service, I am using Angular 2 with components coded in TypeScript. Instead of developing m ...

The parameter 'any' cannot be assigned to the parameter 'never' - Array provided is incompatible

Currently delving into TypeScript and encountering an issue while setting a reducer in redux Toolkit. Here's the code snippet in question: const testSlice = createSlice({ name: "test", initialState: [], reducers: { callApi: (state, ...