0

Almost all of the buttons in my angular 4 app have asynchronous operations associated with them. I'm currently adding a loading spinner to each button manually whenever the button is clicked, and removing it when the operation concludes.

I've realized too late that I could have saved myself a lot of time refactoring etc, if I simply had a custom button component that took an asynchronous event handler and added/removed the spinner on its own.

I'm relatively new to angular 2+ and I'm wondering what a good approach to solving this would be. Should I do a custom component? Or just a custom directive? How do I require the clients of such a component/directive to provide me an asynchronous event handler? Do I use custom attributes or some kind of wrapping around the normal event handling?

I'm not asking for code, just the right features to use, I can take it from there.

Edit:

The loading spinner functionality is currently implemented for each button by showing/hiding an icon element via a boolean property in the corresponding component.

2 Answers 2

1

edited answer

<custom-button [clickFn]="onButtonClickHandler"></custom-button>
Sign up to request clarification or add additional context in comments.

3 Comments

See, the issue is I'd rather the button itself own the loading state, not the parent. Otherwise my parent components with many buttons in them end up with many boilerplate boolean fields.
you could pass in the click function into the custom button's input and handle the Observable/promise from inside the button
I was just considering that
1

If you build a custom component, you can use input property to get any configuration information from the parent/client component and output properties to pass back any events.

Here is an example of the client code using one of my custom components:

        <mh-criteria class='col-md-10'
            [displayDetail]='includeDetail'
            [hitCount]='filteredMovies?.length'
            (valueChange)='onValueChange($event)'>
        </mh-criteria>

And here are the declarations in the associated component:

export class CriteriaComponent implements OnInit {

  @Input() displayDetail: boolean;
  @Input() hitCount: number;

  @Output() valueChange: EventEmitter<string> =
              new EventEmitter<string>();

  // more code here
}

3 Comments

Yes. I added the component code in my answer above.
Is it possible to do an output property that overwrites a built in event (like 'click')?
I'm not sure I understand? Your custom component can catch the click and emit the valueChange event. Is that what you mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.