要在directive中使用ngx-spinner,可以在directive的构造函数中注入NgbModal。然后在指令的ngOnChanges函数中使用它。示例代码如下:
import { Directive, Input, OnChanges } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Directive({
selector: '[appSpinner]'
})
export class SpinnerDirective implements OnChanges {
@Input() appSpinner: boolean;
constructor(private spinner: NgxSpinnerService, private modalService: NgbModal) {}
ngOnChanges() {
if (this.appSpinner) {
this.spinner.show();
const modalRef = this.modalService.open(SpinnerModalComponent, { centered: true, backdrop: 'static' });
modalRef.componentInstance.appSpinner = this.appSpinner;
} else {
this.spinner.hide();
}
}
}
在示例代码中,我们创建了一个“appSpinner”输入,并注入了NgxSpinnerService和NgbModal。
在ngOnChanges函数中,我们检查appSpinner的值。如果它是真的,我们显示一个加载器,并打开一个模态框来遮住页面。如果它是假的,我们隐藏加载器。总之,它允许我们在directive内使用ngx-spinner加载器。