Mock

Definitions

export type IHeader = {
  id?: string;
  title?: string;
  url?: string;
};

Mock

Create a separate file, such a header.mock.ts in your project to store the mock data. You can define the mock data as an array of objects, similar to the actual data you expect to receive from an API.

import { IHeader } from './header.definitions';

export const MockHeader: IHeader[] = [
  {
    id: '1',
    title: 'Home',
    url: 'home',
  },
  {
    id: '2',
    title: 'About',
    url: 'about',
  },
  {
    id: '3',
    title: 'Services',
    url: 'services',
  },
];

Service

ng g s mock-data

Create a service to retrieve the mock data: Generate a service file using the Angular CLI to create a service that will provide the mock data to your components.

import { Injectable } from '@angular/core';
import { MockHeader } from '../components/header/header.mock';

@Injectable({
  providedIn: 'root',
})
export class MockDataService {
  constructor() {}

  getMockData() {
    return MockHeader;
  }
}

Compoment.ts

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IHeader } from './header.definitions';
import { MockDataService } from 'src/app/services/mock-data.service';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
  mockData?: IHeader[];

  constructor(private mockDataService: MockDataService) {}

  ngOnInit() {
    this.mockData = this.mockDataService.getMockData();
  }
}

HTML

<ul>
  <li *ngFor="let item of mockData">
    {{ item.title }}
  </li>
</ul>
Was this page helpful?