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

时间:2018-02-21 10:22:52

标签: angular

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

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

我试图将它应该调用的函数作为输入,但是我需要调用的所有函数都必须在它们绑定到它们所在的实例的地方导出。

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

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

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

1 个答案:

答案 0 :(得分:2)

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

更新:

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

<强>进展-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 });
  }

}

<强>进展-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();
  }
}

<强>进展-spinner.component.html

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

您可以参考以下

WORKING DEMO