How to disable a Button in TypeScript

How to disable a Button in TypeScript

To disable a button in Typescript, you can use the setAttribute method and add the attribute disabled. Let’s read this article to learn more.

Disable a Button in TypeScript

Use setAttribute method

The button element has an attribute called disabled that will help you disable the button so that we can use the setAttribute method to add the disabled attribute to disable a button.

Syntax:

element.setAttribute(‘name’,’value’)

Parameters: 

  • name: name of the attribute that you want to set to your element.
  • value: the value you want to set to your attribute.

Here the disabled attribute is a boolean attribute, so you won’t need to set a value.

Example:

<body>
    <button class="btn">This button will be disabled</button>
</body>
// Select the button
const btn = document.querySelector(".btn");

// Use setAttribute to disable the button
btn?.setAttribute("disabled", "");

The result:

The result in the browser:

If you want to remove the disabled attribute, you can use the removeAttribute method.

Example:

// Select the button
const btn = document.querySelector(".btn");

// Use setAttribute to disable the button
btn?.setAttribute("disabled", "");

// remove the attribute
btn?.removeAttribute("disabled");

You can apply this way and add some conditions to make the button disabled conditionally.

Example:

// Select the button
const btn = document.querySelector(".btn");

// Add event to the button
btn?.addEventListener("click", () => {
    // Use setAttribute to disable the button
    btn?.setAttribute("disabled", "");
});

The result:

As you see, I added a condition that only when I click on the button, it will be disabled.

Use css 

Disabling means that your user cannot click on the button, and the user can see it. So another way for you to make the button disable is you can create a special class name disable, then you can add css property that makes your button look disabled.

Example:

<body>
    <button class="btn">Click to disable the button</button>
</body>
// Select the button
const btn = document.querySelector(".btn");

// Add event for the button
btn?.addEventListener("click", () => {
     btn.classList.add("disabled");
});
.disabled {
    border: solid #999999;
    background-color: #cccccc;
    color: #666666;
    pointer-events: none;
}

The result:

Here I changed some colors to make the button look like it is disabled, and the pointer-events property set to none makes the button cannot the target of the click.

You can read more about DOM and how the Typescript interacts with the browser here.

Summary

In this article, I showed you how to disable a Button in TypeScript. I recommend you use the setAttribute method and then add the disabled attribute. It is easier to do. Good luck to you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *