Angular 属性 绑定目标可以改变组件 属性

Angular property binding target can change component property

我是Angular4的新手,在看官方教程https://angular.io/tutorial, I came across the Master/Detail component (https://angular.io/tutorial/toh-pt3)时,他们在英雄列表组件和英雄详情组件之间做了属性绑定:

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

这里直接引用教程:

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.

如果您检查代码,app-hero-detail 允许通过输入字段更改 hero.name 参数。令我惊讶的是,当更改hero.name字段时,selectedHero.name值也发生了变化(您可以查看live demon https://stackblitz.com/angular/moymegapmypx)。

有什么我想念的吗?这不应该是一种单向绑定吗(selectedHero 更改英雄而不是其他方式)? 我相信对此有一个解释。

hero-details 组件从父组件接收 selectedHero 对象(准确地说,是对该对象的引用)作为输入。然后可以通过输入字段修改同一个对象,但由于我们仍然引用从父级传递的同一个对象,因此更改也会反映在那里。

那是因为您将对英雄实例的引用传递给 child,实际上两者是相同的 object。如果您尝试通过创建一个新英雄来更改 hero 的值,您会看到它 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