What is the equivalent of ngShow and ngHide in Angular 2+?

后端 未结 18 2379
离开以前
离开以前 2020-11-22 14:46

I have a number of elements that I want to be visible under certain conditions.

In AngularJS I would write

stuff
18条回答
  •  情深已故
    2020-11-22 15:22

    For anybody else stumbling across this issue, this is how I accomplished it.

    import {Directive, ElementRef, Input, OnChanges, Renderer2} from "@angular/core";
    
    @Directive({
      selector: '[hide]'
    })
    export class HideDirective implements OnChanges {
      @Input() hide: boolean;
    
      constructor(private renderer: Renderer2, private elRef: ElementRef) {}
    
      ngOnChanges() {
        if (this.hide) {
          this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'hidden');
        } else {
          this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'visible');
        }
      }
    }
    

    I used 'visibility' because I wanted to preserve the space occupied by the element. If you did not wish to do so, you could just use 'display' and set it to 'none';

    You can bind it to your html element, dynamically or not.

    
    

    or

    
    

提交回复
热议问题