Home > Net >  Hide component based on internal value
Hide component based on internal value

Time:10-06

In my component I'm calling a service. When the result is empty I want to set the component to 'hidden', because I don't want an empty bootstrap column.

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

I tried with setting an @output variable, but this didn't work.

@Output() hideComponent: boolean = false

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

P.S. The 'col-6' class has to be on this level, because nested inside the component template it doesn't work.

Any ideas?

CodePudding user response:

One way is that you can refer to the child component variable value from the parent:

  • Within child component do the following:
  hideComponent: boolean = false;

  ngOnInit(): void {
    this.hideComponent = true;
  }
  • Within parent you can do:
<app-streams
  #appstreams
  class="col-6"
  [style.display]="appstreams.hideComponent ? 'none' : 'block'"
></app-streams>

Working example: https://stackblitz.com/edit/angular-ivy-xghere?

Other way of solving this is to use two way binding to share variable hideComponent between parent and child as follows:

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

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

Within the parent component you can do:

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

Working example: https://stackblitz.com/edit/angular-ivy-tnr5fs?

CodePudding user response:

I would flip the logic and apply the ngIf to a div with the col class and have that house the component. That wayyou only get the div if its not hidden and the component doesn't have to worry about the presentation logic.

<div  class="col-6" *ngIf="!hideComponent">
    <app-streams></app-streams>
</div>

And if you cannot have that structure then you can HostBind() a class to the parent based on the variable in the child.

CodePudding user response:

You can set the visibility style attribute with style binding:

<app-streams class="col-6" [style.visibility]="hideComponent? 'visible' : 'hidden'"</app-streams>

In component, on service subscription set hideComponent = true if result is empty false otherwise.

  • Related