首页 文章

在角度4中,我如何制作一个可重复使用的按钮组件,它可以在单击时启用微调器

提问于
浏览
1

我喜欢创建一个可重复使用的按钮组件,它可以在单击时启用微调器,并在函数结束时禁用微调器 .

我尝试过使用按钮组件中的eventEmitter . 但是按钮不知道它调用的函数何时结束,所以它不知道何时停止微调器 .

我试图将它应该调用的函数作为输入,但是我需要调用所有需要调用的函数,它们被绑定到它们所在的实例 .

不能以某种方式挂钩(click)=“doStuff()”并在调用doStuff之前启动微调器并在doStuff结束时隐藏微调器=)

我做了这个例子来展示我在找什么https://stackblitz.com/edit/angular-generalbutton-handlingspinner?file=app/app.component.html

我期待看到你能想到的东西=)

1 回答

  • 2

    你可以做的是创建一个服务,它将显示和隐藏布尔属性作为observable . 然后,您可以创建具有按钮和微调器的可重用组件 . 然后在该组件中,您可以导入服务并随时调用show和hide,并订阅该服务并将show和hide布尔值附加到您的微调器 .

    UPDATE :

    您可以使用@Input在方法结束后进行微调器显示和隐藏 . 将要执行的函数传递给可重用按钮组件,并在按钮组件中执行该功能 . 并在执行后停止微调器 . 当方法在按钮组件内执行时,它会等待异步操作完成然后停止微调器 .

    progress-spinner.service.ts

    export class ProgressSpinnerService {
    
      constructor() { }
    
      private loaderSource = new Subject<ProgressSpinnerState>();
    
    // Observable string streams
      loaderStateChanged$ = this.loaderSource.asObservable();
    
      show() {
        this.loaderSource.next(<ProgressSpinnerState>{ show: true });
      }
      hide() {
        this.loaderSource.next(<ProgressSpinnerState>{ show: false });
      }
    
    }
    

    progress-spinner.component.ts

    export class ProgressSpinnerComponent implements OnInit {
    
      @Input() onClickFunction : any;
    
      show: boolean = false;
      private subscription: Subscription;
    
      constructor(
        private loaderService: ProgressSpinnerService
      ) {
        this.subscription = loaderService.loaderStateChanged$
            .subscribe((state: ProgressSpinnerState) => {
                this.show = state.show;
            });
      }
    
      async startLoader(){
         this.loaderService.show();
         console.log("1 - The fire method on the button has started and the spinner is shown");
         await this.onClickFunction();
         console.log("4 - Now the fire method is done and the spinner is told to stop");
         this.loaderService.hide();
       }
    
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }
    

    progress-spinner.component.html

    <button (click)="startLoader()">Start Loader</button>
    <div *ngIf="show">
      <div>
        <mat-progress-spinner>
        </mat-progress-spinner>
        
    <div>Please wait....</div> </div> </div>

    你可以参考下面

    WORKING DEMO

相关问题