开发学院

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

教程正文

Angular 6 模板

  Angular 6使用类似于Angular 4的标签<ng-template>,未采用Angular2中的<template>。因为<template>标签和html <template >标准标签之间存在名称冲突。

  现在,让我们将模板与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语句,并将调用模板条件1,else条件2。

  模板将按如下方式调用

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

  如果条件为真,则调用条件1模板,否则调用条件2。

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 6 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,因此打印条件2模板。如果单击该按钮,将调用相应的模板。如果你检查浏览器,你会发现你永远不会在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