1

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).

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

See also OnChanges livecycle callback.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.