如何在AngularJS中使用*ngIf else

如何在AngularJS中使用*ngIf else

介绍: ngIf指令用于显示或隐藏angular应用程序的部分。它可以被添加到任何标签,它是一个正常的HTML标签,模板或选择器。它是一个结构性指令,意味着它包括基于条件约束的布尔值的模板。当表达式评估为真时,它会运行/显示 “then “子句中给出的模板。或者当表达式的值为false时,显示 “else “子句中给出的模板。如果else子句中没有任何内容,它将默认显示空白。

语法:

ngIf with an "else" block
JavaScript
<div *ngIf="condition; else elseStatement">
    when condition is true.
</div>
<ng-template #elseStatement>
    when condition is false.
</ng-template>
<!--It can be seen that the else 
    clause refers to ng-template,
    with the label #elseStatement -->
HTML

它内部创建了两个<ng-template>,一个用于 “then “语句,另一个用于 “else”。因此,当ngIf的条件为真时,未标记的内容<ng-template>会被显示。而当false时,标记的内容就会<ng-template>运行。

步骤:

1.正如我们所知,ngIf else语句对具有布尔类型的变量起作用。创建一个angular应用程序,并将其移至src/app。首先,我们需要在app.component.ts中定义一个变量 “check”,值为true或false。

<!-- Define a variable say "check" with
value true/false in app.component.ts -->
    import { Component } from '@angular/core';
      
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
      
    export class AppComponent {
      check:boolean = true;
    }
JavaScript

2.定义好变量后,移到app.component.html,用bootstrap类创建两个分部。移动到angular应用程序中,编写命令npm install bootstrap 。第一个分部是为 “真 “条件而设的,里面的分部<ng-template>是为假条件而设的。我们已经声明检查为真,所以我们得到一个绿色的分割线,表示条件为真。如果检查是假的,就会显示一个红色的分部,表示条件为假。

<!-- *ngIf else -->
    <div class="container-fluid">
        <div class="row bg-success 
                text-light h1 justify-content-center
                align-items-center" *ngIf="check;
                else elseStatement" 
                style="height:150px">Condition true
        </div>
      
      <ng-template #elseStatement>
        <div class="row bg-danger
                text-light h1 d-flex 
                justify-content-center align-items-center"
                style="height:150px">Condition false
        </div>
      </ng-template>
    </div>
HTML

输出:
如何在AngularJS中使用*ngIf else?

输出:
如何在AngularJS中使用*ngIf else?

Advantages:

  • 编程语言的 “if “块支持逻辑运算符,所以它支持 “ngIf”。它支持所有的逻辑运算符,如AND, OR, NOT等。
  • ngIf有助于避免无法读取未定义属性的错误。假设有一个名为 “student “的绑定属性。我们试图访问学生的 “name “子属性,它的值是 “Santosh”。如果学生是空的,它将返回未定义的错误。因此,如果我们在访问子属性之前检查是否为空,我们将使用*ngIf防止错误。
    <!--This may error-->
    <div>
      {{student.name}}
    </div>
      
    <!--check using ngIf-->
    <p *ngIf="student">
      {{student.name}}
    </p>
HTML

输出:

Santosh
JavaScript
  • ngIf 与 Hidden:你可能会想,既然我们在 HTML5 中有隐藏属性,为什么还要使用 ngIf 呢?是的,它们做的是同样的工作,但仍有区别。hidden 属性将所选元素从 DOM 中隐藏起来,但该元素仍然存在于 DOM 中。而 ngIf 则是将选定的部分从 DOM 中删除。它并不干预CSS
    <!--check is defined in component.ts 
        with value true (boolean)-->
    <div [hidden]="!check">
      Show this only if "check" is true
    </div>
HTML

输出:

Show this only if "check" is true
JavaScript

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册