我正在尝试为我的应用创建自定义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();
}
);
}
}
但是我遇到了错误 错误TypeError:无法读取未定义的属性'nativeElement' 在SpinnerComponent.show
答案 0 :(得分:3)
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; }
请尝试此操作。
答案 1 :(得分:0)
如果您要解决,那么
<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"; };
答案 2 :(得分:0)
使用forwardRef
forwardRef用于我们需要引用的令牌时 DI的用途已声明,但尚未定义。在以下情况下也使用 我们在创建查询时使用的令牌尚未定义。
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();
}
);
}
}