Search code examples
angulartypescript2-way-object-databinding

Angular 2 Two-way Binding updates mock service constant


As I was going through the "Tour of Heroes" Angular 2 tutorial, I have noticed that when ngModel changes, the change propagates to other components utilizing the same object. But when I tried to log the mock service constant HEROES on the console, its value also changed.

mock-heroes.ts

import { Hero } from './shared/hero.model';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
];

hero.service.ts

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

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    console.log(HEROES); // print the constant HEROES value
    return Promise.resolve(HEROES);
  }
}

hero-detail.component.html

<div *ngIf="hero">
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="hero.name" placeholder="name"/>
  </div>
</div>

heroes.component.html

<h3>My Heroes</h3>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>
<hero-detail [hero]="selectedHero"></hero-detail>

heroes.component.ts

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

@Component({
  selector: 'my-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes);
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}

The HeroService is injected from the AppModule providers array (global service provider).

Changing the name from "Narco" to "Narcosssss" through the input:

enter image description here

updates the constant HEROES as seen on the console:

enter image description here

Can someone please explain to me how it works?


Solution

  • Your hero objects have the same reference throughout your app. So, if you change the referenced object. The property will change wherever it's been referenced.