Angular 2 指令


A 指示 是一个自定义 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


The ngif element 用于将元素添加到 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}} Newbiego </div> 

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

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

ngIf

ngFor


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

语法

*ngFor = 'let variable of variablelist'

该变量是一个临时变量,用于显示 变量列表 .

现在让我们看一个如何使用 *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 和名称参数。

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

ngFor