首页 > 解决方案 > 在父组件中隐藏子组件

问题描述

我只想在子组件完成 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
        })
    }
}

但它不起作用,即使服务正确响应,子组件也永远不会显示

标签: angulartypescriptrxjs

解决方案


你不能这样做,因为组件只会在*ngIf' 条件为真时被渲染(即初始化)。

相反,我建议在您的子组件中完全处理它,通过将可观察的 HTTP 调用映射到booleanHTTP 调用完成后,以确定是否应该呈现组件内容。

您可以尝试以下方法:

父组件.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>

推荐阅读