1

There are some situations where it's better to keep a hidden component in DOM. In Vue there the v-show in addition to the v-if. But in Angular I didn't find an equivalent? So the best solution is to use s.th. like [ngStyle]="{ 'display': showMe ? 'block' : 'none' }"?

EDIT: I also could set the hidden attribute, which should have a very similar effect, e.g. [hidden]="!showMe".

Is there actually a reason why Vue.js did include v-show instead of simply using :hidden?

Peter T.
  • 2,927
  • 5
  • 33
  • 40
  • 1
    Your example is indeed correct. `v-show` is also just toggling `display` under the hood. Or you can also use the HTML attribute `hidden`, e.g. `[hidden]="!showMe"` – Ricky Mo Jun 02 '23 at 08:11
  • Thanks, you're absolutely right. I edited the question to give it a slightly different directly :-) – Peter T. Jun 02 '23 at 08:28
  • 1
    The second question might be opinion based, I don't expect there to be any official statements on why Vue has made their framework design choices. Maybe the reason is that `hidden` works with CSS and can be overridden by simply specifying the `display` CSS property on the element, like pointed out in the linked answer. This is why I needed to add the following global styles in my applications: `[hidden] { display: none !important }`. So `v-show` and `:hidden` may not lead to the same result. – JSON Derulo Jun 02 '23 at 08:35
  • Frameworks are all about convenience. You can technically do everything with vanilla javascript. Frameworks exist to help you write less. If there is some code developers found they write so frequently, they make a shorthand for it. – Ricky Mo Jun 02 '23 at 08:39
  • You can also use:`[style.display]="!showMe?'none':null"` – Eliseo Jun 02 '23 at 08:48
  • 1
    Ironically, Vue borrowed it from Angular – Estus Flask Jun 02 '23 at 09:26

1 Answers1

1

v-show is simply sugar syntax for adding style="display: none". While I'm not aware of anything like that built into angular, it's trivial to build your own directive that will achieve the same result (code not tested):

@Directive({
  selector: 'appHidden',
})
class HiddenDirective {
 @Input('appHidden')
 isHidden: boolean = false;

 @HostBinding('style.display')
 get displayStyle() {
   return this.isHidden ? 'none' : undefined;
 }
}

Usage:

<div [appHidden]="shouldBeHidden"></div>
Xymanek
  • 1,357
  • 14
  • 25
  • The problem with this approach is that it overrides element's own display style, in case it's specified – Estus Flask Jun 02 '23 at 09:28
  • 2
    @Estus Flask when `isHidden` is false, the `undefined` for host binding will cause angular to remove `display` from the element styles, thus restoring whatever the CSS-specified value is – Xymanek Jun 02 '23 at 10:12