Angular4-templates
提供:Dev Guides
Angular 4-テンプレート
*Angular 4* は、Angular2で使用される *<template>* の代わりに、タグとして *<ng-template>* を使用します。 Angular 4が *<template>* を *<ng-template>* に変更した理由は、 *<template>* タグとhtml *<template>* 標準タグの間に名前の競合があるためです。 これは完全に廃止される予定です。 これはAngular 4の主要な変更点の1つです。
*if else* 条件とともにテンプレートを使用して、出力を確認します。
app.componentl
<!--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またはelse 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.componentl',
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);
}
}
ブラウザでの出力は次のとおりです-
変数 isavailable はfalseなので、condition2テンプレートが出力されます。 ボタンをクリックすると、それぞれのテンプレートが呼び出されます。 ブラウザを調べると、domでspanタグを取得できないことがわかります。 次の例は、同じことを理解するのに役立ちます。
ブラウザを調べると、domにspanタグがないことがわかります。 domの Condition is invalid from template があります。
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>
then条件を削除すると、ブラウザーに*「Condition is valid」メッセージが表示され、domでもspanタグを使用できます。 たとえば、 *app.component.ts では、 isavailable 変数をtrueにしています。