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

标签 javascript angular

假设我有以下场景:

@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;
  }
}

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

谢谢!

最佳答案

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

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

import {Component,Input} from 'angular2/core';

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

}

查看此插件:https://plnkr.co/edit/ka9fd9?p=preview .

关于javascript - 更改属性时重新渲染 Angular2 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36037610/

相关文章:

javascript - 无法从 Outlook 功能区打开链接是 javascript API 而不是弹出窗口

javascript - 测试 rxjs : How to fake-click an element and check the resulting stream with marble diagrams?

javascript - 删除 ngFor 中的前 4 个字符

angular - Angular 2 组件中的 Google AdSense 广告?

javascript - 制定 toast 指令

javascript - 尽管文件存在,但获取 'Module not found'

angular - EventSource 在 Angular 4 中不起作用

angular - 调用post请求但在网络 Angular 5上调用get请求

javascript - 将多个字符串从 html 表单传递到 javascript 函数?

angular - 如何在 Angular Testing 中检索 ngClass 的值?