Angular 2 中 ngIf 的概念
在 Angular 2 中,ngIf
指令是 Angular 2 中最直接和最有用的指令之一。它用于根据表达式的评估有条件地显示或隐藏 HTML 元素。
ngIf
指令评估一个表达式,如果它评估为真,它将呈现给定的元素。如果不是,它根本不会渲染该元素。
当多个视图共享共同特征时,该指令有助于减少 DOM 元素的数量。
这篇文章将教你关于 ngIf
的一切。
隐藏 CSS 中的组件与 Angular 2 中的 ngIf
即使 HTML 缺少 if
语句,CSS 中的 show 和 visibility 属性也可用于隐藏页面的各个部分。
我们可以在 HTML 元素中添加或删除 CSS 属性,并使用 JavaScript 从页面中隐藏元素。但是,这与 ngIf
不同。
如果一个元素隐藏在 ngIf
中,则该元素在页面上不存在。
如果你使用 Chrome 开发工具调查该页面,你将不会在 DOM 中看到任何 HTML 元素。
Angular 2 中 ngIf
中的表达式
ngIf
指令接受任何有效的 Typescript 短语作为输入,而不仅仅是布尔值。接下来将评估表达式的彻底性以确定是否应显示该元素。
除了布尔值,我们还可以向 ngIf
发送文本、数组和对象。
在 Angular 2 中使用 ngIf
的步骤
在 Angular 2 中使用 ngIf
需要遵循以下步骤:
- 编写一个将被评估为真或假的表达式。
- 用左括号和右括号将表达式括起来,例如 (true || false)。
- 添加管道字符|在左括号和右括号之间。
- 使用步骤 1 中的表达式将 ngIf 指令添加到你的模板中。
例子:
让我们在 Angular 2 中讨论一个完整的 ng-if
示例。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:
`<h1 *ngIf=" 34< 100" >I'm Adil</h1>
<h1 *ngIf="3>1" > I'm John</h1>
<h1 *ngIf="46<200" >I'm Steven</h1>`,
})
export class AppComponent {
}
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。