我正在使用这个加载指令作为一个按钮.我的问题是,在使用该指令时,它会将进度加载器附加到按钮下方,而不是按钮内部.
我已经通过控制台记录了this.elementRef.nativeElement
,它返回了正确的按钮元素.
button-loader.directive.ts个
import { Directive, ElementRef, Input, ViewContainerRef, Renderer2 } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { MatProgressBar } from '@angular/material/progress-bar';
@Directive({
selector: '[buttonLoader]'
})
export class ButtonLoaderDirective {
progressElement: any;
@Input() set buttonLoader(value: boolean) {
this.toggle(value);
}
constructor(
private viewContainerRef: ViewContainerRef,
private matButton: MatButton,
private renderer: Renderer2,
private elementRef: ElementRef) {
this.loadComponent();
}
loadComponent() {
this.viewContainerRef.clear();
// Create Component
const matProgress = this.viewContainerRef.createComponent(MatProgressBar);
matProgress.instance.mode = 'indeterminate';
// Move it
this.progressElement = matProgress.injector.get(MatProgressBar)._elementRef.nativeElement
this.renderer.appendChild(this.elementRef.nativeElement, this.progressElement);
// Add custom class
this.elementRef.nativeElement.classList.add('mat-load-button');
}
toggle(condition: boolean) {
condition ? this.show() : this.hide()
}
show() {
this.progressElement.style.opacity = '0.7';
this.matButton.disabled = true;
}
hide() {
this.progressElement.style.opacity = '0';
this.matButton.disabled = false;
}
}
HTML个
<button
[buttonLoader]="true"
mat-raised-button
color="primary"
>
Save
</button>
Currently how it looks个
Here's how I want it to look个