更改属性时重新渲染 Angular2 组件

Re-render Angular2 component when property is changed

本文关键字:新渲染 Angular2 组件 属性      更新时间:2023-09-26

假设我有以下情况:

@Component({
  selector: 'my-app',
  template: `
      <my-component
          [myAttr]="myAttr"
      ></my-component>
      <button (click)="onClick()">Click</button>
  `,
  directives: [MyComponent]
  })
  class AppComponent {
     myAttr: number = 1;
  onClick() {
      this.myAttr += 1;
  }
}

因此,当单击该按钮时,我想重新渲染组件,以便在底层组件上填充新值。我也尝试了双向绑定,但在这种情况下没有多大意义,因为它是单向绑定。所以问题是我如何触发更新?

谢谢!

事实上,如果您对输入使用插值(像您所做的那样)并在父组件中更新,则该值会自动更新到您的子组件中。

以下是定义子组件的方法:

import {Component,Input} from 'angular2/core';
@Component({
  selector: 'my-component',
  template: `
    <div>{{myAttr}}</div>
  `
})
export class MyComponent {
  @Input()
  myAttr: number;
}

看到这个 plunkr: https://plnkr.co/edit/ka9fd9?p=preview.

你不需要触发任何东西。由于角度变化检测的工作方式,更新会自动发生。

Angular

猴子修补了在 Angular "区域"内定义的所有异步事件(例如您的 (click) 事件绑定),因此在 onClick() 事件处理程序完成后,Angular 将自动运行更改检测。

更改检测会注意到myAttr绑定到输入属性 MyComponent,它会自动将新值传播到子组件。 更改检测还会注意到(如果我们使用 Thierry 的例子)属性myAttr绑定到div,它会自动将新值传播到divtextContent属性。 角度变化检测完成,然后浏览器注意到 DOM 变化并更新您在屏幕上看到的内容。

您说得对,但是还有一件事 - 应该使用哪个事件来检测子组件中的此更改以执行某些逻辑。例如,我可以看到ngAfterContentCheck事件被触发,但是它触发了多次,我似乎无法找出原因。

还有一件事 - 我可以从子组件推送更新吗?例如,当子组件发生更改(来自用户输入或类似内容)时,控制 myAttr 的 my-app 组件将进行更新。我在这里考虑 React 的方式,所以我不确定这是正确的方法。