Angular 中的 if...else 语句
我们将介绍如何在 Angular 应用程序中使用 if
语句并讨论示例。
在 Angular 中使用 if
语句
在编程中,if
语句是逻辑块。这些条件语句告诉计算机在特定条件为真或假时要做什么。
在 Web 应用程序的现代时代,if
语句使程序员的生活更容易理解何时根据条件运行特定代码块。
我们可以通过不同的方式使用 *ng-if
或我们将在示例中讨论的其他简单方法在 Angular 中使用 if
语句。
让我们使用以下命令创建一个新应用程序:
# angular
ng new my-app
在 Angular 中创建我们的新应用程序后,我们将使用此命令转到我们的应用程序目录。
# angular
cd my-app
现在,让我们运行我们的应用程序来检查所有依赖项是否安装正确。
# angular
ng serve --open
然后,在 app.component.ts
中,我们将变量 statement
设置为 false
。我们将使用这个变量来执行我们的代码。
# angular
statement = false;
现在,在 app.component.html
中,我们将使用变量 statement
创建一个模板,如果我们将变量设置为 true
,它将显示声明为真的内容。
如果我们将变量设置为 false
,它将显示语句为 false。
# angular
<hello name="{{ name }}"></hello>
<h2>{{ statement ? 'This statement is True' : 'This statement is false' }}</h2>
让我们测试我们的应用程序,看看它在更改值 statement
时是否有效。
输出:
更改语句的值,将其设置为 true
,然后检查它是如何工作的。
输出:
因此,如你所见,当我们更改 statement
变量的值时,代码会执行并使用简单的语句方法显示我们想要查看的值。
让我们想象一个我们想要在执行 if-else
语句的 div 中显示的块。我们可以使用 *ng-if
语句并将 ids 设置为我们想要在条件正确或错误时显示的块。
我们将设置一个新变量 element
为 1。app.component.ts
中的代码如下所示。
# angular
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
statement = true;
element = 1;
}
在 app.component.html
中创建一个模板。我们将有一个带有*ng-if
语句的 div,它将显示一个块 trueBlock
,如果 element
的值不是 1,那么它将显示 id 为 falseBlock
的块。
<div *ngIf="element == 1; then trueBlock; else falseBlock"></div>
<ng-template #trueBlock><button>Login</button></ng-template>
<ng-template #falseBlock><button>Logout</button></ng-template>
让我们看看它是如何工作的。
输出:
尝试更改 element
的值并检查它是如何工作的。
# angular
element = 2;
输出:
正如你在上面的示例中所看到的,我们可以使用*ng-if
语句并调用块的 id 轻松显示代码块。
相关文章
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 事件。