官术网_书友最值得收藏!

Adding conditions to the template

The event handler in the previous section sets the property collapsed to false but that does not modify the template. In normal code, we would have written if (this.collapsed) { ... }. In templates, we cannot use that, but we can use ngIf.

Directives

A directive is an extension to normal HTML tags and attributes. It can define custom behavior. A custom component, such as the About page, can be seen as a directive too. The ngIf condition is a built-in directive in Angular. It is a custom attribute that displays the content if the specified value is true.

The template tag

If a piece of a component needs to be shown a variable an amount of times, you can wrap it in a template tag. Using the ngIf (or ngFor) directive, you can control how often it is shown (in case of ngIf, once or zero times). The template tag will look like this:

<template [ngIf]="collapsed"> 
  <div>Content</div> 
</template> 

You can abbreviate this as follows:

<div *ngIf="collapsed">Content</div> 

It is advised to use the abbreviated style, but it's good to remember that it is shorthand for the template tag.

Modifying the about template

Since ngIf is a built-in directive, it doesn't have to be imported. Custom directives need to be imported. We will see an example of using custom components later in this chapter. In the template, we can use *ngIf now. The template will thus look like this:

  template: ` 
    <h2>About</h2> 
    This widget shows the weather forecast of 
    <a [href]="'https://maps.google.com/?q=' + encodedLocation"> 
      {{ location }} 
    </a>. 
    The next 24 hours are shown under 'Today' and the forecast        of 24-48 hours ahead under 'Tomorrow'. 
    <br /> 
 <a *ngIf="collapsed" href="javascript:;" (click)="show()">Show more</a> 
 <div *ngIf="!collapsed"> 
 The forecast uses data from <a >Open Weather Map</a>. 
 <br /> 
 <a href="javascript:;" (click)="hide()">Hide</a> 
 </div> 
  ` 
}) 

The class body does not have to be changed. As you can see, you can use expressions in the *ngIf bindings, which is not surprising as it is a shorthand for one-way variable bindings.

主站蜘蛛池模板: 黔江区| 尖扎县| 泊头市| 石林| 陇西县| 迁安市| 平凉市| 廊坊市| 达日县| 兴宁市| 余干县| 滦南县| 洛浦县| 徐水县| 宁德市| 日土县| 新野县| 清远市| 辉南县| 密山市| 乌兰浩特市| 安康市| 延吉市| 曲阜市| 龙南县| 阿巴嘎旗| 上犹县| 碌曲县| 渝北区| 会昌县| 宁夏| 成都市| 红河县| 白银市| 鹤峰县| 公主岭市| 泰来县| 邵东县| 五莲县| 广南县| 内丘县|