我正在尝试为我的应用程序创建一个自定义Spinner组件,所以我创建了
spinner.component.ts
export class SpinnerComponent implements AfterViewInit {
@ViewChild("spinner") spinner: ElementRef;
constructor() { }
ngAfterViewInit(): void {
this.spinner.nativeElement.style.display = "none";
}
public show = (): void => { this.spinner.nativeElement.style.display = "block"; };
public hide = (): void => { this.spinner.nativeElement.style.display = "none"; };
}
spinner.component.ts
<img #spinner src="assets/images/dotSpinner.gif" class="loading"/>
而我正试图在我的其他组件中控制这个微调器,比如
sample.component.ts
import { SpinnerComponent } from "../spinner/spinner.component";
export class SimpleComponent {
private spinner: SpinnerComponent = new SpinnerComponent();
constructor() {}
actionHandler = (data: any): void => {
this.spinner.show();
this.clientActionService.subscribe(
data => {
this.spinner.hide();
this.clientAction = data;
},
err => {
this.spinner.hide();
}
);
}
}
但是我收到错误ERROR TypeError:无法在SpinnerComponent.show中读取未定义的属性“nativeElement”
spinner.component.ts // html代码
<img *ngIf="isShowSpinner" src="assets/images/dotSpinner.gif" class="loading"/>
<button (click)="show()"> Show </button>
<button (click)="hide()"> Hide </button>
spinner.component.ts //打字稿代码
public isShowSpinner: boolean = false;
constructor() { }
public show() { this.isShowSpinner = true; }
public hide() { this.isShowSpinner = false; }
请试试这个。
如果你想要解决方法
<img
[ngStyle]="{'display': displayVal}"
src="assets/images/dotSpinner.gif"
class="loading"/>
打字稿代码
display = "none";
public show = (): void => { this.displayVal = "block"; };
public hide = (): void => { this.displayVal = "none"; };
使用forwardRef
当我们需要为DI目的引用的令牌被声明但尚未定义时,使用forwardRef。当我们尚未定义创建查询时使用的令牌时,也会使用它。
import { SpinnerComponent } from "../spinner/spinner.component";
export class SimpleComponent {
constructor(constructor(@Inject(forwardRef(() => SpinnerComponent )) private ref:any)) {}
actionHandler = (data: any): void => {
this.ref.show();
this.clientActionService.subscribe(
data => {
this.ref.hide();
this.clientAction = data;
},
err => {
this.ref.hide();
}
);
}
}