简体   繁体   中英

@ViewChild returns undefined - Angular 2

I'm trying to use @ViewChild to get the DOM element that I need. I have the following component that describes my problem:

import {Component, ViewChild, ElementRef, OnInit, Input} from "@angular/core";


@Component({
  selector: 'some-comp',
  template: `

  <input
    #myInputOut
    type="text"
    class="google-place-input"
    placeholder="Type to search..">

   <span class="row form-group">
     <required-input
       class="col-12 has-danger"
       [label]="'somel:'"
       [controlName]="'somel'"
       [form]="group"
      </required-input>
    </span>

 <div class="row form-group2 required">
    <label class=" col-3 control-label" for="street">label:</label>
    <input #myInputIn class="col-7" id="someid" placeholder="Type to search.." /></div>
`
})
export class someClass implements OnInit{

  @ViewChild('myInputOut') myInputOut: ElementRef;
  @ViewChild('myInputIn') myInputIn: ElementRef;


  private element: HTMLInputElement;
  private element2: HTMLInputElement;

    constructor(  private databaseService : DatabaseService,
               private router : Router){

  }


  ngOnInit(){
    this.element = this.myInputOut.nativeElement;
    this.element2 = this.myInputIn.nativeElement;
  }
}

For some reason myInputOut returns properly but myInputIn returns undefined. How can I solve this?

Looks like you are commenting the input or at least started to

 <!--  <div class="row form-group2 required">
    <label class=" col-3 control-label" for="street">label:</label>
    <input #myInputIn class="col-7" id="someid" placeholder="Type to search.." />

"<!--" shouldn't be there

You will be able to access ViewChild queries only inside ngAfterViewInit(). It's not available in ngOnInit() hence you are getting undefined.

There are some errors in the code, kindly fix it and try again.

<required-input
   class="col-12 has-danger"
   [label]="'somel:'"
   [controlName]="'somel'"
   [form]="group"

there should be a closing tag --> [form]="group" >

<!--<div class="row form-group2 required">

Remove " <!-- " before the <div class="row form-group2 required"> and close it properly with </div>

Finally, declare input type type="text"

<input #myInputIn type="text" class="col-7" id="someid" placeholder="Type to search.." />

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