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

后端 未结 18 2381
离开以前
离开以前 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:20

    If you just want to use the symmetrical hidden/shown directives that AngularJS came with, I suggest writing an attribute directive to simplify the templates like so (tested with Angular 7):

    
    import { Directive, Input, HostBinding } from '@angular/core';
    
    @Directive({ selector: '[shown]' })
    export class ShownDirective {
      @Input() public shown: boolean;
    
      @HostBinding('attr.hidden')
      public get attrHidden(): string | null {
        return this.shown ? null : 'hidden';
      }
    }
    

    Many of the other solutions are correct. You should use *ngIf where ever possible. Using the hidden attribute can have unexpected styles applied, but unless you are writing components for others, you probably know if it is. So for this shown directive to work, you will also want to make sure that you add:

    [hidden]: {
      display: none !important;
    }
    

    to your global styles somewhere.

    With these you can use the directive like so:

    stuff

    with the symmetrical (and opposite) version like so:

    stuff

    To add on to the shoulds - yous should also us a prefix like so [acmeShown] vs just [shown].

    The main reason I used a shown attribute directive is for converting AngularJS code to Angular -AND- when the content that is being hidden contains container components that cause XHR round trips. The reason I don't just use [hidden]="!myVar" is that often enough it is more complicated like: [hidden]="!(myVar || yourVar) && anotherVar" - yes I can invert that, but it is more error prone.[shown]` is simply easier to think about.

提交回复
热议问题