Search code examples
angulartypescriptgoogle-pay

Google Pay Button Disable on Condition


I need to disable google-pay-button in angular. Following is the stackblitz link

Stackblitz

I have tried [disabled], [attr.disabled]. But nothing seems to work. I have to disable this google pay button on some conditions. Helps are highly appreciated.

Google Pay Button Docs


Solution

  • We can extend the functionality of the Google Pay Button component using a directive. In this case we can have a disabled directive that can accept a component property if it needs to be disabled.

    Create a gpayDisabled directive:

    import { Directive, ElementRef, Input } from '@angular/core';
    import { interval } from 'rxjs';
    
        @Directive({
          selector: '[gpayDisabled]',
        })
        export class GpayDisabledDirective {
          @Input() gpayDisabled = false;
          constructor(el: ElementRef) {
            const btnTimer = interval(200).subscribe(() => {
              let gPayButton = el.nativeElement.querySelector(
                '.gpay-card-info-container'
              );
              if (gPayButton) {
                 gPayButton.disabled = this.gpayDisabled;
                 if (this.gpayDisabled) {
                  gPayButton.style.opacity = 0.5;
                }
                btnTimer.unsubscribe();
              }
            });
          }
        }
    

    Declare this in declaration array of the module, for example:

    declarations: [AppComponent, GpayDisabledDirective]
    

    Then in the template, we can use this directive like this:

     <google-pay-button
        [gpayDisabled]="isGpayDisabled"
        environment="TEST"
        [buttonColor]="buttonColor"
        [buttonType]="buttonType"
        [buttonSizeMode]="isCustomSize ? 'fill' : 'static'"
        [paymentRequest]="paymentRequest"
        [style.width.px]="buttonWidth"
        [style.height.px]="buttonHeight"
        (loadpaymentdata)="onLoadPaymentData($event)"
      ></google-pay-button>
    

    where isGpayDisabled is a component property, either true or false.

    Stackblitz demo.