目录

Angular 2 - 指令( Directives)

directive是一个自定义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

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

语法 (Syntax)

*ngIf = 'expression'

如果表达式的计算结果为true,则会添加相应的内容,否则不会添加元素。

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

Step 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;
}

Step 2 - 现在在app.component.html文件中,添加以下代码。

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

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

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

输出 (Output)

ngIf

ngFor

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

语法 (Syntax)

*ngFor = 'let variable of variablelist'

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

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

Step 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。

Step 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参数。

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

输出 (Output)

ngFor
↑回到顶部↑
WIKI教程 @2018