「ion-segment」で初回表示後に項目を追加または削除する
コンポーネント「ion-segment」の項目「ion-segment-button」を、初回表示後に追加または削除する場合の方法についてです。
目次
- コード
- ngAfterViewInit()を利用する場合の注意点
- 参考リンク
コード
HTML
<ion-segment [(ngModel)]="selectedCategory">
<ion-segment-button *ngFor="let category of categories" value="{{ category.id }}">
{{category.name}}
</ion-segment-button>
</ion-segment>
<button ion-button (click)="addCategory()">カテゴリ追加</button>
コンポーネント
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'example',
templateUrl: 'example.html'
})
export class Page1 implements OnInit {
@ViewChild(Segment) segment: Segment;
constructor(}
selectedCategory: string = "book";
categories: any = []:
ngOnInit() {
this.categories = [
{ id: "book", name: "本" },
{ id: "game", name: "ゲーム" }
];
}
addCategory(): void {
let no = this.categories.length + 1;
this.categories.push({ id: "category" + no, name: "カテゴリ" + no });
// ion-segmentの初期化
setTimeout(() => {
if (this.segment) {
this.segment.ngAfterViewInit();
}
});
}
}
初回表示後に「ion-segment」の個数が変わる場合は、上記のようにデータ追加後「this.segment.ngAfterViewInit()」を実行してion-segmentの初期化を行わないと、表示または操作に不具合が発生します。
削除時も同様のタイミングで「this.segment.ngAfterViewInit()」を呼び出します。
ngAfterViewInit()を利用する場合の注意点
「ngOnInit()」ではなく、下記のように「ngAfterViewInit()」で「ion-segment」に表示するデータをセットしている場合も注意が必要です。
コンポーネント
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'example',
templateUrl: 'example.html'
})
export class Page1 implements OnInit {
@ViewChild(Segment) segment: Segment;
constructor(}
selectedCategory: string = "book";
categories: any = []:
ngAfterViewInit() {
this.categories = [
{ id: "book", name: "本" },
{ id: "game", name: "ゲーム" }
];
// ion-segmentの初期化
setTimeout(() => {
if (this.segment) {
this.segment.ngAfterViewInit();
}
});
}
}
ngAfterViewInit()でデータをセットしている場合、データセット後に「this.segment.ngAfterViewInit()」を実行しないと正常に動作しません。