1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Angular】*ngForで簡単にループする配列を変更する方法

Last updated at Posted at 2022-07-27

はじめに

HTMLは同じでも処理によってループさせる配列を変更したいことがあり、悩んだ末にこの方法にたどり着きました。
同じように悩む方の参考になればと思います。
※前提としてcomponentでどうしても配列を同じにすることができなかった場合を想定しています。

バージョン

・Angular: 9.1.11
バージョンの確認方法については過去記事に記載しております。

結論

*ngForの中で三項演算子を使用して配列を変更させています。

judge.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-judge',
  templateUrl: './judge.component.html'
})
export class JudgeComponent {
  isNumber: boolean = true;
  numberArray: number[] = [1, 2, 3, 4, 5];
  stringArray: string[] = ["イチロウ","ジロウ","サブロウ","シロウ","ゴロウ"];

  constructor() { }
}
judge.component.html
出力結果:
<div *ngFor="let element of (changeFlag? numberArray : stringArray);">
  {{ element }}
</div>

<!-- changeFlagがtrueの場合 -->
<!-- 
  出力結果:
  1
  2
  3
  4
  5
-->

<!-- changeFlagがfalseの場合 -->
<!-- 
  出力結果:
  イチロウ
  ジロウ
  サブロウ
  シロウ
  ゴロウ
-->

*ngIfで書いた場合

この場合だと同じHTMLを二つ書かなければならない。

judge.component.html
<div *ngIf="changeFlag; then thenBlock else elseBlock">出力結果:</div>
<ng-template #thenBlock>
  <div *ngFor="let element of numberArray;">
    {{ element }}
  </div>
</ng-template>
<ng-template #elseBlock>
  <div *ngFor="let element of stringArray;">
    {{ element }}
  </div>
</ng-template>

おまけ

for...ofでも同じことができます。

judge.component.ts
const changeFlag: boolean = true;
const numberArray: number[] = [1, 2, 3, 4, 5];
const stringArray: string[] = ["イチロウ","ジロウ","サブロウ","シロウ","ゴロウ"];

for(let element of (changeFlag? numberArray : stringArray)) {
  console.log(element);
}
// 1
// 2
// 3
// 4
// 5

参考文献

Angular:NgForOf
Angular:NgIf
mdn_web_docs:条件 (三項) 演算子
TypeScript Deep Dive 日本語版:for...of

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?