angular - 在父组件中隐藏子组件
问题描述
我只想在子组件完成 http 调用后才在父组件中呈现子组件,但这对我不起作用,子组件不显示...
child selector in parent component
<app-child-component *ngIf="alert" (alert)="propagar($evento)"></app-child-component >
export class ParentComponent implements OnInit {
alert = false;
propagar(evento: boolean) {
this.alert = evento;
}
export class ChildComponent implements OnInit {
@Output alert = new EventEmitter<boolean>();
ngOnInit() {
this.childComponentService.getSomething().subscribe(response => {
if(this.response.code === 200)
this.alerta.emit(true);//here I just want the child component to be displayed
})
}
}
但它不起作用,即使服务正确响应,子组件也永远不会显示
解决方案
你不能这样做,因为组件只会在*ngIf
' 条件为真时被渲染(即初始化)。
相反,我建议在您的子组件中完全处理它,通过将可观察的 HTTP 调用映射到boolean
HTTP 调用完成后,以确定是否应该呈现组件内容。
您可以尝试以下方法:
父组件.html
<app-child-component></app-child-component>
child.component.ts
export class ChildComponent implements OnInit {
ready$: Observable<boolean>;
ngOnInit() {
// Assign it to an observable to avoid handling subscribe/unsubscribe within the component class.
ready$ = this.childComponentService
.getSomething()
.pipe(map((response) => response.code === 200));
}
}
child.component.html
<!-- Wrap all your child component template with ng-container -->
<ng-container *ngIf="ready$ | async">
<!-- Your child components stuff here which will be rendered only once the HTTP call is completed -->
</ng-container>
推荐阅读
- python - 如何通过 pySerial 从 Python 发送 int 或 string 并在 C 中转换为 int 或 String
- c# - 如何在 c# Visual Studio 2019 的单元测试方法中使用控制台或终端来显示输出并接收来自用户的输入?
- python - def() 外与 def() 内
- c++ - 堆和栈之间的距离
- redux - 测试ngrx:调度动作并期待商店
- magnolia - 获取 magnolia cms 类型 [mgnl:area] 的页面属性、系统属性和所有子节点的属性
- spring - Spring集成流SFTP:模式过滤器不起作用
- git - Git rebase --abort 使我所有的提交都消失了,有没有办法恢复它们?
- linux - 如何从 CSV 输出中删除 NONREF 和 RETURN 行
- android - Android 在每次启动应用程序时运行一段代码,但在应用程序最小化和重新打开时不运行