0

I have input box inside two divs that render conditionally.

html

<div ngIf="show==true">
<input #ref />
</div>

<div ngIf="show==true">
<input #ref />
</div>

.ts

@ViewChild('ref ') ref : ElementRef;

ngOnInit(){

 if(someCondition){
  show = true;
 }

Observable.fromEvent(this.ref .nativeElement, 'keyup');
}

It shows the undefind ref as ref variable declared before ngOnInit

I believe we cannot initialize viewchild later,

What could be alternate solution.

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Md. Parvez Alam
  • 4,326
  • 5
  • 48
  • 108

1 Answers1

2

you need to access that viewchild component like as below. Means you have to make use of "ngAfterViewInit" (implement AfterViewInit ), as child component doesnt get avaiable when "ngOnit" runs

  @ViewChild('ref ') ref : ElementRef;

  ngAfterViewInit() {
    console.log('Values on ngAfterViewInit():');
    console.log("ref:", this.ref);
  }  
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263