You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ngShow实现当插值变量person等于指定值时显示元素?

Using ngShow to Display Elements Based on the person Variable Value

Hey there! Let me break down exactly how to use AngularJS's ngShow directive to show an element only when your person variable equals a specific value (like family).

Basic Implementation

The ngShow directive relies on a boolean expression — when the expression evaluates to true, the element is displayed; when it's false, the element gets hidden (via display: none under the hood).

For your scenario, you just need to check if person strictly equals the string 'family' (using === for type-safe comparison, which is the recommended practice). Here's how to apply it:

<h2 class="mat-title" style="text-align:center;">Register as a {{person}}</h2>

<!-- Element to show only when person is 'family' -->
<div ng-show="person === 'family'">
  This content will only appear when the person variable is set to 'family'!
</div>

Bonus: Handling Multiple Values

If you ever need to show the element for multiple values (e.g., family or admin), you can extend the expression with logical OR operators:

<div ng-show="person === 'family' || person === 'admin'">
  This content shows for family or admin users!
</div>

Quick Note for Angular 2+ Users

If you're working with a newer Angular version (2+), ngShow doesn't exist anymore. Instead, you'd use *ngIf (which removes the element from the DOM entirely) or [hidden] (similar to ngShow's CSS-based hiding):

<!-- Using *ngIf in Angular 2+ -->
<div *ngIf="person === 'family'">
  Content visible only for family users
</div>

内容的提问来源于stack exchange,提问作者CodeHip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:15:33