ngForによる繰り返し処理
繰り返しタグの表示を行いたい場合は、「ngFor」という構造ディレクテイブを使う。構造ディレクテイブとはテンプレートの中に記述できる、特別な役割を持った命令みたいなものである。
hello.component.html
<divid=“body”>
<p*ngIf=“visible”(click)=“doClick()”class=“red”>
This is TRUE message.
</p>
<ul>
<li*ngFor=“let item of data”>{{item}}</li>
</ul>
</div>
hello.component.ts
import {Component,OnInit }from‘@angular/core’;
@Component({
selector: ‘app-hello’,
templateUrl: ‘./hello.component.html’,
styleUrls: [‘./hello.component.css’]
})
export classHelloComponentimplementsOnInit {
data:string[];
constructor() {
}
ngOnInit() {
this.data = [
‘最初の項目‘,
‘2番目の項目‘,
‘3番目の項目‘
];
}
}
ngSwitchを使ってみる
いくつもの中から一つを表示する、というような場合に用いられるのがngSwitchという構造的ディレクテイブである。ngSwitchは[ngSwitch]タグの中に選択肢タグを組み込む。
下記のようなものを作る
hello.component.html
<divid=“body”>
<h1>{{title}}</h1>
<p>{{message}}</p>
<div[ngSwitch]=“switch”>
<p*ngSwitchCase=“‘one'”>First paragraph!</p>
<p*ngSwitchCase=“‘two'”>second paragraph!</p>
<p*ngSwitchCase=“‘three'”>third paragraph!</p>
<p*ngSwitchCase=“‘default'”>default paragraph!</p>
</div>
<select#sel (change)=“doSelect(sel.value)”>
<option>one</option>
<option>two</option>
<option>three</option>
</select>
</div>
hello.component.ts
import {Component,OnInit }from‘@angular/core’;
import {Title }from‘@angular/platform-browser’;
@Component({
selector:‘app-hello’,
templateUrl:‘./hello.component.html’,
styleUrls: [‘./hello.component.css’]
})
exportclassHelloComponentimplementsOnInit {
title:string;
message:string;
switch:string;
constructor() {
}
ngOnInit() {
this.title =‘Hello-app’;
this.message =‘select menu:’;
this.switch =‘one’;
}
doSelect(val:string) {
this.switch =val;
}
}
コメント