Efficient code for varying layouts of disabled Angular Material buttons

I've been wondering if there's a simpler way to customize the appearance of a disabled button using Angular Material.

Currently, I achieve this by utilizing an ng-container and ng-template. While this method gets the job done, the code is not very concise because the primary difference between the two buttons is just the presence of class="disabled", which should only be applied when the button is disabled. I understand that there are other distinctions as well, but those are related to attributes like (click) for the enabled button which are irrelevant in the disabled state. Similarly, having the disabled property on the enabled button serves no purpose.

                <ng-container *ngIf="disabledNext; else next">
                    <button mat-button class="disabled" type="button" [disabled]="disabledNext">
                        Next
                    </button>
                </ng-container>
                <ng-template #next>
                    <button mat-raised-button (click)="nextDate()" type="button">
                        Next
                    </button>
                </ng-template>

I'm seeking a solution similar to this approach, but I am unsure if it is feasible

<button mat-button-raised class="disabledNext ? disabled : ''">Next</button>

OR some form of CSS selector that can target buttons with the disabled property set to true

button.disabled { ... }

Answer №1

  1. Use the [class.classname]="condition" syntax to conditionally set classes
  2. To conditionally set disabled, use
    [attr.disabled]="condition ? true : null"

If the button is disabled, the click handler will not fire. You can also exit the handler early if the button is disabled.

Keep in mind that the button will be disabled if the disabled attribute is present, even if it's an empty string. Using a value of null for the enabled state ensures that the attribute won't be added to the HTML.

<button [class.disabled]="disabled" type="button" 
    [attr.disabled]="disabled ? true : null" (click)="nextDate()">
  Next
</button>

This is a demonstration using pure Angular.

You can dynamically add the mat-raised-button class when the button is not disabled.

<button mat-button [class.mat-raised-button]="!disabled">
</button>

See the live demo here: https://stackblitz.com/edit/angular-e8gkca

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

What is the best way to ensure that table cells containing images resize without any issues?

I need help with centering and resizing an image on a screen. The image is divided into small images within cells, but I can't seem to get it right. Despite trying various solutions and spending hours resizing the table and images, the final output a ...

Encountering an issue with NgRx store where the property 'products' is not recognized on the type 'ActionCreatorProps<{ payload: Product[]; }>' while attempting to build a reducer

Currently, I am delving into the @ngRx/store package within my Angular 14 App. My primary goal is to establish a basic store capable of containing a simple object Array. Here is an excerpt from my action file: import { Product } from 'src/app/data-mod ...

No matter how many times I modified the code in the ReactDOM.render() method within my index.js file, the end result remained unchanged

When I ran npx create-react-app my-app, and then proceeded to cd my-app and npm start, a browser opened on localhost:3000. While looking at the index.js file, I noticed that the ReactDOM.render() method included the following code: ReactDOM.render( <Rea ...

Gradual decline in content loading due to ngrx store actions with payloads

When dispatching actions to the store, there is a noticeable decrease in content load efficiency from http requests due to incremental deficiencies. Surprisingly, requests that do not involve store logic or handling the content of the http requests themsel ...

Elaborate Conditional Statements

For my R loop to simulate football matches in a season, I need to write a long if statement. Currently, I am using the following code to simulate match results: mod3=glm(formula = Score ~ as.factor(Attack) + as.factor(Defence) +as.factor(Home)+Division, f ...

Tips for adapting the position of a floating div according to its height and environment

Important Note: The code below utilizes the rubuxa plugin for handling JS sortables. Javascript: function querySelector(expr){return document.querySelector(expr)} var container = querySelector('.ITEST'); var sortable = Sortable.create(container, ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

Adjusting the content of mat-cards to fill in blank spaces

I have encountered an issue with the alignment in a list using mat-card. Here is my current layout: https://i.stack.imgur.com/VKSw4.jpg Here is the desired layout: https://i.stack.imgur.com/8jsiX.jpg The problem arises when the size of content inside a ...

Attempting to incorporate adaljs within TypeScript code

I am currently in the process of building an application using Angular2 and TypeScript. I have come across the need to incorporate ADALJS into my project. Since ADALJS only supports Angular1, I have decided to utilize just adal.js for this particular task. ...

The duration required to render DOM elements

Trying to determine the best method for measuring the rendering time of DOM elements in a web browser. Any tips? I'm currently developing an application that involves significant DOM manipulation as part of comparing the performance between Angular 1 ...

Accessing Nested Arrays in Angular 8: Retrieving Data in HTML Template from Multiple Layers of Arrays

Hello there. I'm using an API that gives me the following data: (4) [{…}, {…}, {…}, {…}] 0: dueDate: "2018-03-26T00:00:00" priority: {priorityId: 1, priorityName: "Critical", priorityColor: "red"} statuses: Array(1) 0: ...

Using various span elements with distinct alignment within an h1 tag in Bootstrap 5

How can I nest three span tags inside an h1 tag, aligning them differently? The first on the left, the second in the center, and the third on the right. Can this be achieved using Bootstrap or does it require custom CSS? ...

Why is an additional return statement necessary in Angular when attempting to retrieve data from a custom service?

As a newcomer to javascript and angular, I have successfully created a custom service in angular that connects to a URL and retrieves information. My goal is to return response.data instead of just the response itself. var getAlldatas = function($http) ...

Make multiple images in one row resize proportionally instead of wrapping them to the next line

My phone's screen is small and I want the three images to remain in the same row. In case they don't fit, they should shrink proportionately to maintain alignment (refer to image at the bottom). Consider the code snippet below: <div id="exam ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Is it possible to create a mouse-following effect with lighting using Javascript

Recently, I've been honing my Javascript skills and decided to create a follow-mouse function. After successfully implementing it, I started brainstorming a new concept that I'm unsure is achievable. Is there a way to develop an "orb of vision" ...

Is there a way to make the footer adapt to the varying heights of the grid sections as they grow in size?

Currently, I am facing an issue with the positioning of the page footer. Despite my efforts, it does not remain at the bottom as intended. Please refer to the image for a visual representation of the problem. How can this be rectified? It is worth noting ...

Angular: Displaying data in a list format from a multidimensional array

My data structure is as follows: { 'TeamLeader': 'Andrew', 'subordinates': [{ 'Name': 'Daniel', 'subordinates': [{ 'Name': 'Stev ...

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Leveraging the X-Send module for efficiently delivering css, javascript, and image files

I am in the process of setting up a file server that currently serves downloadable files such as .doc and .zip perfectly using X-Send. Is it also possible to use X-Send for serving text-based (css/javascript) or image files? I believe this method is quite ...