Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using Ionic Framework and I create a new directive to IonButton component, it actually disables the button and then enable it back when a process is completed (lets say it is a saving progress).

Here is my button template

<ion-button fill="clear" color="primary" expand="block" (click)="acceptRequest()" [submitButton]="true">
    ACCEPT
</ion-button>

[submitButton] is an Input in my directive to enable the click listener.

I can disable the button and modify its content after click using a @HostListener,

@HostListener('click') onButtonClick() {
const spinnerContent = `<ion-spinner name="dots"></ion-spinner>`
    if (this.isSubmitButton) {
        const spinnerContent = `<ion-spinner name="dots"></ion-spinner>`
        this.buttonElement.disabled = true;

        const btnChildren = this.el.nativeElement.children;
        this.oldElement = this.el.nativeElement.cloneNode(true);

        for (let child of btnChildren) {
          this.renderer.removeChild(this.el.nativeElement, child);
        }
        this.el.nativeElement.innerHTML = spinnerContent;
    }
}

The problem is how can I implement when to re-enable the button after the saving process is complete. I am saving the data inside acceptRequest() method using RxJS. Let's say I am saving to the API, and re-enable the button.

Some example I know is IonRefresher, we can easily call event.target.complete() to complete the loading spinner and hide the refresher from the page.

Thank you.

Edit: I know that it is easier to use [disabled] inside the button instead of using directives, but I need to change the child nodes of the element, and can be used easily. So I think of using directive as the solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can viewChild the button, and cast it to the directive, while exposing an API on the directive to stop the spinner (and reenable everything you want).

in the directive, you add a function you want to expose, and then in your component, on the template, you add #myBtn:

<ion-button #myBtn fill="clear" color="primary" expand="block" (click)="acceptRequest()" [submitButton]="true">
    ACCEPT
</ion-button>

and in the component itself, you can cast the child to the directive:

@ViewChild("myBtn", { read: SubmitDirective }) myBtn: SubmitDirective;

and then, after you are done with your API call, you can call the function on the directive you just created (this.myBtn.stopSpinner())

here is a new working stackblitz


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...