Angular 2 - 指令

指令是一个自定义HTML元素,用于扩展HTML的强大功能. Angular 2具有以下指令,这些指令作为BrowserModule模块的一部分被调用.

  • ngif

  • ngFor

如果查看app.module.ts文件,您将看到以下代码和BrowserModule模块的定义.通过定义此模块,您将可以访问2个指令.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule ({
   imports:      [ BrowserModule ],
   declarations: [ AppComponent ],
   bootstrap:    [ AppComponent ]
})
export class AppModule { }

现在让我们详细查看每个指令.

ngIf

ngif 元素用于向HTML代码添加元素(如果它的计算结果为true),否则它不会将元素添加到HTML代码中.

语法

* ngIf ='expression'

如果表达式求值为true,则添加相应的元素,否则不添加元素.

现在让我们看看如何使用* ngif指令的示例.

第1步 : 首先将属性添加到名为appStatus的类中.这将是布尔类型.让我们保持这个值为真.

import { Component } from '@angular/core';  

@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
})

export class AppComponent {
   appTitle: string = 'Welcome';
   appStatus: boolean = true;
}

第2步 : 现在在app.component.html文件中,添加以下代码.

<div *ngIf = 'appStatus'>{{appTitle}} Tutorialspoint </div>

在上面的代码中,我们现在有* ngIf指令.在指令中,我们正在评估appStatus属性的值.由于属性的值应该评估为true,这意味着div标签应该显示在浏览器中.

一旦我们添加上面的代码,我们将在浏览器中获得以下输出.

输出

ngIf

ngFor

ngFor 元素用于基于For循环条件的元素.

语法

* ngFor ='让变量列表的变量'

变量是一个临时变量,用于显示变量列表中的值.

现在让我们看看如何使用* ngFor指令的示例.

第1步 : 首先将属性添加到名为appList的类中.这将是可用于定义任何类型的数组的类型.

import { Component } from '@angular/core';
 
@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
})

export class AppComponent {
   appTitle: string = 'Welcome';
   appList: any[] = [ {
      "ID": "1",
      "Name" : "One"
   },

   {
      "ID": "2",
      "Name" : "Two"
   } ];
}

因此,我们将appList定义为具有2个元素的数组.每个元素都有2个子属性,分别为ID和Name.

第2步 : 在app.component.html中,定义以下代码.

<div *ngFor = 'let lst of appList'> 
   <ul> 
      <li>{{lst.ID}}</li> 
      <li>{{lst.Name}}</li> 
   </ul> 
</div>

在上面的代码中,我们现在使用ngFor指令迭代appList数组.然后我们定义一个列表,其中每个列表项是数组的ID和name参数.

一旦我们添加上面的代码,我们将在浏览器中获得以下输出.

输出

ngFor