home

Angular Baby Steps

Example - 1

hero.ts

export class Hero {
    id: number;
    name: string;
}

mock.heroes.ts

import {Hero} from "./hero";

export const HEROES: Hero[] = [
    {
        name: 'Koray',
        id: 1
    }, {
        name: 'Toprak',
        id: 2
    }
];

hero.service.ts

import {Injectable} from '@angular/core';
import {HEROES} from "./mock-heroes";
import {Hero} from "./hero";

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

    getHeroes(): Hero[] {
        return HEROES;
    }
}

hero.component.ts

import {Component, OnInit} from '@angular/core';
import {HeroService} from "../hero.service";
import {Hero} from "../hero";

@Component({
    selector: 'app-hero',
    templateUrl: './hero.component.html',
    styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
    constructor(private heroService: HeroService) {
    }

    ngOnInit() {
    }

    getHeroes(): Hero[] {
        return this.heroService.getHeroes();
    }
}

hero.component.html

<table>
    <tr>
        <th>Hero ID</th>
        <th>Hero Name</th>
    </tr>
    <tr *ngFor="let hero of getHeroes()">
        <td>{{hero.id}}</td>
        <td>{{hero.name}}</td>
    </tr>
</table>

app.component.html

<h1>Tour of Heroes</h1>
<app-hero></app-hero>