Search code examples
htmlangularhidemultiple-columnsangular-ng-if

how to hide column when input is empty in Angular


I have three flex column and I want the middle column to hide when the input is empty.

My goal is to hide the middle column first, show the middle column when the user start typing and hide again when the input is empty.

I was able to do the first two but not sure how to hide it again

I believe I might have to do something with *ngIf in the input or inside middle column but I'm new to angular and not sure how.

My Input
           <input matInput [formControl]="inputCtrl" [(ngModel)]="searchText" 
           (ngModelChange)="searchTextChanged($event)" placeholder="Search" class="input"

My Middle Column

    <div class="center" *ngIf="showColumn">

TS

  showColumn = false;


  ngOnInit(): void {

    this.inputCtrl.valueChanges
      .pipe(takeUntil(this.death$))
      .subscribe((value: string) => {
        this.showColumn = true;
      });

Solution

  • You can use searchTextChanged($event)

    Add this function to your app:

        searchTextChanged(event){
        if(this.searchText == '')
        {
        this.showColumn = false;
        }
         else{
         this.showColumn = true;
        }
    

    or

    you can do something like this

    this.inputCtrl.valueChanges
          .pipe(takeUntil(this.death$))
          .subscribe((value: string) => {
            if(value == ''){
             this.showColumn = false;
            }
           else{ 
                 this.showColumn = true;
             }
    
          });
    

    Hope this helps!