properties - 属性更改时重新构建/重新渲染 Angular2 组件

标签 properties angular components

如何实现?

我的子组件

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

@Component({
selector: 'my-component',
template: `
    <div>In child component - myAttr = {{ myAttr1 }}</div>
`
})
export class MyComponent  {
  @Input() myAttr: number;
  myAttr1:number;
 ngOnInit()
 {
  this.myAttr1=this.myAttr*10;
 }

}

主要组成部分

import {Component} from 'angular2/core';
import {MyComponent} from './sub.component';

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

  onClick() {
    console.log('Click in the parent component');
    this.myAttr += 1;
  }
}

我需要更新每次点击的值。应该有一个直接的方法,否则 Angular2 团队应该考虑这个

最佳答案

您应该使用 ngOnChanges 来检测何时在您的子组件中更新 myAttr:

@Component({
  selector: 'my-component',
  template: `
    <div>In child component - myAttr = {{ myAttr1 }}</div>
  `
})
export class MyComponent  {
  @Input() myAttr: number;
  myAttr1:number;
  ngOnInit() {
    this.myAttr1=this.myAttr*10;
  }

  ngOnChanges() { // <------
    this.myAttr1=this.myAttr*10;
  }
}

这允许检测何时更新 myAttr 输入属性并相应地更新 myAttr1 一个。

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

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

相关文章:

javascript - Angular 2 CRUD 组件

ios - 如何子类化 UIViewController 并快速添加属性?

javascript - 使用函数作为对象属性

c# - DelegateCommand的重载方法

angular - 如何以 Angular 覆盖现有组件?

javascript - 无法将一个 Svelte 组件导入到另一个组件中

c# - Visual Studio 不会使用 ReadOnlyAttribute(true) 使属性变灰

angular - 以 Angular 上传文件的补丁值

javascript - Typescript不使用JS函数(Typeof)

Angular4 @Input() 父组件传值给子组件