Angular 中的 if...else 语句

Rana Hasnain Khan 2022年4月20日
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 时是否有效。

输出:

使用简单方法在 Angular 中使用 if else 语句

更改语句的值,将其设置为 true,然后检查它是如何工作的。

输出:

使用具有真值的简单方法在 Angular 中使用 if else 语句

因此,如你所见,当我们更改 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>

让我们看看它是如何工作的。

输出:

Angular 显示块中的 if else 语句与 true 语句

尝试更改 element 的值并检查它是如何工作的。

# angular
element = 2;

输出:

带有错误语句的 Angular 显示块中的 if else 语句

正如你在上面的示例中所看到的,我们可以使用*ng-if 语句并调用块的 id 轻松显示代码块。

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn