开发学院

您的位置:首页>教程>正文

教程正文

Angular 4 模板

Angular 4 模板

  Angular 4使用<ng-template>作为标签,而不是Angular2中使用的<template>。Angular 4将<template>更改为<ng-template>的原因是因为<template>标签和html <template>标准标签之间存在名称冲突。这是Angular 4的主要变化之一。

  现在,让我们将模板与if else条件一起使用,并查看输出。

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)" name = "month">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable;then condition1 else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>
<button (click) = "myClickFunction($event)">Click Me</button>

  对于Span标记,我们添加了带有else条件的if语句,满足条件的时候调用模板condition1,否则condition2。

  模板的调用如下:

<ng-template #condition1>Condition is valid from template</ng-template>
<ng-template #condition2>Condition is invalid from template</ng-template>

  如果条件为真,则调用condition1模板,否则调用condition2。

app.component.ts

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

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = false;
   myClickFunction(event) {
      this.isavailable = false;
   }
   changemonths(event) {
      alert("Changed month from the Dropdown");
      console.log(event);
   }
}

  浏览器中的输出如下所示:

app_component_ts_output.jpg

  变量isavailable为false,因此打印condition2模板。如果单击该按钮,将调用相应的模板。如果你检查浏览器,你会发现你永远不会在DOM中得到span标签。以下示例将帮助您理解相同的内容。

inspect_the_browser.jpg

  如果你检查浏览器,你会发现DOM没有span标签。从DOM中的模板来看,它具有无效的条件。

  html中的下面一行代码将帮助我们在DOM中获得span标签。

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)" name = "month">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>

<button (click)="myClickFunction($event)">Click Me</button>

  如果我们移除当时的条件,我们会在浏览器中得到“Condition is valid”的消息,并且span标签也可以在DOM中找到。例如,在app.component.ts中,我们将isavailable变量设为true。

app_component_ts_isavailable.jpg