简体   繁体   中英

angular2 displaying computed data in template

I am just starting to use Angular2 and engaged the following problem. Template (Main Component):

<span *ngFor="#data of dataset" >
    <data-widget [data]="data"></data-widget>
</span>

Template (Widget Component):

<div>{{someCompValue}}</div>

The value of someCompValue is need to be created from set of properties inside the data member variable.

Where should I inject the code to compute the someCompValue? I tried to do it inside constructor() but that moment the data is not yet assigned (=null).

@Component({
  selector: 'data-widget',
  template`<div>{{someCompValue}}</div>`})
class DataWidget {
  @Input() data;
  ngOnChanges(change)  {
    this.someCompValue = doCalculationBasedOnData();
  }
}

See also OnChanges livecycle callback.

Use ngOnInit ( ref ):

Initialize the directive/component after Angular initializes the data-bound input properties.

So in the component:

@Component(...)
export class DataWidget {
    @Input data: Xxxx;

    constructor() { ... }

    ngOnInit() {
        // this.data should be set and ready to use here
    }
}

EDIT: Looking at the answer from Günter Zöchbauer, a note : use ngOnInit if the data is to be calculated only once at component initialization ; use ngOnChanges (as per Günter's answer) if data is to be calculated at the beginning and recalculated every time the inputs change .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM