1

I have 2 sibling components in Angular2:

<test1 *ngIf="data"  [data] = "makes" #test1R></formModel>
<testing *ngIf="data" [test1Ref]="test1R"></testing>

Component "Testing" has a function that call a function of test1 Component:

export class Testing{

    @Input() test1Ref: test1Component;
    constructor() { }

    testFunction($event){
        this.test1Ref.hello();
    }

My problem is that this.test1Ref is undefined, because test1 component has *ngIf (<test1 *ngIf="data") ,
but without *ngIf I have an error in test1 component for input value ([data] = "makes").
How can I pass component reference with *ngIf

1 Answer 1

2

In short, you can't. You'll have to hide the component if !data , that way your local variable #test1R will still be set.

<test1 [hidden]="!data" [data]="makes" #test1R></test1>

Then null check inside test1 in ngOnInit() to avoid the exception.

If you can only execute certain code once data is set, do it like this:

Declare data as an Input inside your test1 component:

export class Test1 {
  @Input() data: any;
}

By declaring it as an @Input everytime the value changes, Angular will call ngOnChanges, so now you can do this:

ngOnChanges(changes: SimpleChanges) {
  if(changes['data'] && changes['data'].currentValue) {
    //Do something once data is set.
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, I understand, I don't like because if I retrieve data with async call , check if data exists in ngInit is always useless..so I have to handle some event?
Updated answer to show how to handle null checking for async.
No probs :-) have fun!

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.