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
  • 704,970
  • 168
  • 1,303
  • 1,425
Md. Parvez Alam
  • 4,049
  • 3
  • 36
  • 93

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
  • 170,430
  • 35
  • 234
  • 261