Disable button after a click in angular using directive

Prateek Singh
2 min readDec 31, 2021

--

Background: need of directive to disable a button

We have a use case where the user has requested for the button to be disabled immediately after the click.

The first option is to set the disabled property of a button. But this feature we have to do for all buttons and a few places we have observables and validations. Considering all cases we have decided to use a directive.

Implementation

Create a new directive via CLI— ng g d disable-after-click

add @Input directive to set disabled property. The set property will accept a boolean input or an observable<boolean>.

@HostBinding decorator has been used for binding input disabled attribute.

Will be adding a two-way binding on the disabled property so it could share the button state with the consumer component.

Now will be setting a listener for the click event of a button.

In OnInit event will be setting the subscription for the observable if present

In the onDestroy event, the observable will be unsubscribed if has been set.

ExportAs: has been used so that an instance of the directive could be used in a template.

coerceBooleanProperty: has been used to parse the input to boolean. This is a new prop added in v12.

Demo

Code

articles explaining hostbinding and two-way binding

--

--

Prateek Singh
Prateek Singh

Written by Prateek Singh

I am a full-stack developer. Working on angular, .net, and azure. I like to read about CSS, web design, and authentication.

Responses (1)