Custom types in angular

41 Views Asked by At

How to create custom type in Angular. can anyone please show it how to implement it at the component level? I know about the below part

type Programmer = {
  name: string;
  knownFor: string[];
};
const ada: Programmer = {
  name: 'Ada Lovelace',
  knownFor: ['Mathematics', 'Computing', 'First Programmer']
};

But how to actually create it and use it in the Angular component? Thanks.

1

There are 1 best solutions below

0
Adil On

Create custom type using interface. file name Programmer.ts.

Programmer.ts

export interface Programmer {
  name: string;
  knownFor: string[];
}

MyComponent

import { Component } from '@angular/core';
import { Programmer } from './programmer'; // import the custom type

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  ada: Programmer = {
    name: 'Ada Lovelace',
    knownFor: ['Mathematics', 'Computing', 'First Programmer']
  };
}

HTML

<div>
  <h2>{{ ada.name }}</h2>
  <p>Known for:</p>
  <ul>
    <li *ngFor="let item of ada.knownFor">{{ item }}</li>
  </ul>
</div>