首页 > 解决方案 > 根据内部值隐藏组件

问题描述

在我的组件中,我正在调用服务。当结果为空时,我想将组件设置为“隐藏”,因为我不想要一个空的引导列。

<app-streams class="col-6" [hidden]="hideComponent"</app-streams>

我尝试设置 @output 变量,但这不起作用。

@Output() hideComponent: boolean = false

ngOnInit(): void {
    this.hideComponent = true
  }

PS 'col-6' 类必须在这个级别,因为嵌套在组件模板中它不起作用。

有任何想法吗?

标签: angular

解决方案


一种方法是您可以从父组件中引用子组件变量值:

  • 在子组件中执行以下操作:
  hideComponent: boolean = false;

  ngOnInit(): void {
    this.hideComponent = true;
  }
  • 在父母中,您可以执行以下操作:
<app-streams
  #appstreams
  class="col-6"
  [style.display]="appstreams.hideComponent ? 'none' : 'block'"
></app-streams>

工作示例:https ://stackblitz.com/edit/angular-ivy-xghere ?

解决此问题的其他方法是使用在父子之间two way binding共享变量,如下所示:hideComponent

  @Input() hideComponent: boolean = false;
  @Output() hideComponentChange = new EventEmitter<boolean>();

  ngOnInit(): void {
    this.hideComponentChange.emit(true);
  }

在父组件中,您可以执行以下操作:

<app-streams
  class="col-6"
  [(hideComponent)]="hideComponent"
  *ngIf="!hideComponent"
></app-streams>

工作示例:https ://stackblitz.com/edit/angular-ivy-tnr5fs ?


推荐阅读