简体   繁体   English

@ViewChild 返回未定义 - Angular 2

[英]@ViewChild returns undefined - Angular 2

I'm trying to use @ViewChild to get the DOM element that I need.我正在尝试使用 @ViewChild 来获取我需要的 DOM 元素。 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.出于某种原因, myInputOut正确返回,但myInputIn返回未定义。 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().您将只能在 ngAfterViewInit() 中访问 ViewChild 查询。 It's not available in ngOnInit() hence you are getting undefined.它在 ngOnInit() 中不可用,因此您未定义。

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" >应该有一个结束标记 --> [form]="group">

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

Remove " <!-- " before the <div class="row form-group2 required"> and close it properly with </div>删除<div class="row form-group2 required">之前的“ <!-- ”并用</div>正确关闭它

Finally, declare input type type="text"最后,声明输入类型type="text"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM