# TypeScriptで必要なデータだけ代入して表示

Angularに限った話ではないかもしれないですが、


定義された独自クラスのインスンタンス変数に必要なデータだけ代入してテンプレートで表示したい時のやり方について。よくやるので書きます。


```typescript:hoge.model.ts
export class Hoge {
  id: string;
  name: string;
  dateCreated: Date;
  fuga: Fuga;
}
```

このようなモデルが定義されていて、Hoge型のnameプロパティのみ入ったデータを配列で用意してテンプレートで表示させたい時、

```typesript:test.component.ts
import { Hoge } from './hoge.model.ts';

@component({
  selector: 'app-test',
  styleUrl: './test.component.scss',
  templateUrl: './test.component.html'
})

export class TestComponent {
  readonly hoges: Hoge[] = [
    { name: 'sato' },
    { name: 'taro' },
    { name: 'jiro' }
  ] as Hoge[];
}
```
このように記述して表示できます。本来`id`や`dateCreated`など定義されているデータを代入しないとエラーがでますが、`as Hoge[]`とすることで型情報の上書きが行われエラー回避できます。

```html:test.component.html
<div *ngFor="let hoge of hoges">
    {{ hoge.name }}
</div>
```

## 関連記事
https://tips.weseek.co.jp/%E7%94%A8%E8%AA%9E%E9%9B%86/Javascript/Angular/ngFor%E3%81%A7%E6%8C%87%E5%AE%9A%E5%9B%9E%E6%95%B0%E7%B9%B0%E3%82%8A%E8%BF%94%E3%81%99

---

## Page Navigation

- Canonical URL: https://tips.weseek.co.jp/用語集/Javascript/Angular/TypeScriptで必要なデータだけ代入して表示
- Permalink: https://tips.weseek.co.jp/5e51e4683a1f5c0048d0ac82
- Parent: [Angular](/5e393953e848c600487d6a04.md)
- Children: 0 total
- Total descendants: 0
- Siblings: 1 total
  - [ngForで指定回数繰り返す](/5e3fc5c3f5921400485be6d2.md)
- Last updated: 2020-02-23T02:33:12.790Z by deleted_at_1672138060255
- Full page listing (all children regardless of count): https://tips.weseek.co.jp/_api/v3/page-listing/children?id=5e51e4683a1f5c0048d0ac82
