0

I am new to Angular 4, and while reading the official tutorial https://angular.io/tutorial, I came across the Master/Detail component (https://angular.io/tutorial/toh-pt3), there they did a property binding between the heroes list component and the hero details component:

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

Here is a direct quote from the tutorial:

It's a one way data binding from the selectedHero property of the HeroesComponent to the hero property of the target element, which maps to the hero property of the HeroDetailComponent. Now when the user clicks a hero in the list, the selectedHero changes. When the selectedHero changes, the property binding updates hero and the HeroDetailComponent displays the new hero.

If you check the code, app-hero-detail allows to change the hero.name parameter via an input field. What surprised me is that when changing the hero.name field, the selectedHero.name value also changes (you can check the live demon https://stackblitz.com/angular/moymegapmypx).

Is there something I am missing? Isn't this supposed to be a one way binding (selectedHero changes hero but not the other way)? I am sure there is an explanation for this.

4

2 回答 2

1

The hero-details component receives the selectedHero object (to be precise, a reference to that one object) as input from the parent. That same object can then be modified via the input field, but since we are still referencing the same object that was passed from the parent, the change is reflected there as well.

于 2018-05-17T08:11:29.620 回答
1

Thats because you are passing a reference to the hero instance to the child, in effect both are the same object. If you try to change the value of hero by creating a new hero, you can see that its one-way.

export class HeroDetailComponent implements OnInit {
  _hero: Hero;

  @Input('hero')
  set hero(value: Hero) {
    this._hero = Object.assign(new Hero(), value);
  }
  get hero(): Hero {
    return this._hero;
  }

  constructor() { }

  ngOnInit() {
  }

}

https://stackblitz.com/edit/angular-yvzbug?file=src/app/hero-detail/hero-detail.component.ts

于 2018-05-17T08:15:29.147 回答