【发布时间】:2019-03-17 14:13:44
【问题描述】:
我正在尝试为我的应用创建自定义 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();
}
);
}
}
但我遇到了错误 错误类型错误:无法读取未定义的属性“nativeElement” 在 SpinnerComponent.show
【问题讨论】:
-
您不应该手动创建组件实例。使用上面建议的查询(ViewChild,ContentChild)或DI机制。
-
我试过了,但我收到类似 ERROR 错误:StaticInjectorError(AppModule)[SimpleComponent -> SpinnerComponent]: StaticInjectorError(Platform: core)[SimpleComponent -> SpinnerComponent]: NullInjectorError: No provider对于 SpinnerComponent!
-
我确实在 app.module.ts 上注册过
标签: angular typescript angular-directive