【发布时间】:2017-12-03 04:58:25
【问题描述】:
我们的应用中有很多组件。
某些组件需要来自服务器的数据,然后仅显示 html。
在没有数据到来之前,我们需要显示一些加载栏 html。
我想知道是否有任何通用的解决方案?
我可以开始将 *ngIf 放在每个组件中,但我正在考虑更通用的解决方案。
所以目前我正在考虑。
- 创建一个指令
- 在指令中传递对象
- 检查内部指令是否对象可用
- 如果它不可用,则在元素内添加一些 html。
到现在为止,下面的代码已经写好了。
@Directive({
selector: '[appCustomLoad]'
})
export class CustomLoadDirective implements AfterViewInit{
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private renderer: Renderer,
private el: ElementRef) {
}
@Input() set appCustomLoad(shouldAdd: boolean){
// currently i am passing boolean for testing,
// if i use this solution then i will change boolean to any.
// and if object is not null or undefined then we will show loading bar with some msg.
if(shouldAdd){
this.viewContainer.createEmbeddedView(this.templateRef);
}else{
this.viewContainer.clear();
}
}
ngAfterViewInit(): void {
// after view init
}
}
我无法使用指令在我的 div 中添加 html。
我不确定这是不是正确的方法,所以如果您有任何更好的解决方案,请给我一些想法。 p>
【问题讨论】:
-
您的组件架构是什么样的?我猜你可能会在你的根组件中执行你的请求,并用一个
ngIf包装你需要隐藏的任何其他组件?
标签: javascript html angular