angular - @ViewChild 返回未定义 - Angular 2
问题描述
我正在尝试使用 @ViewChild 来获取我需要的 DOM 元素。我有以下描述我的问题的组件:
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;
}
}
由于某种原因myInputOut
正确返回但myInputIn
返回未定义。我该如何解决这个问题?
解决方案
您将只能在 ngAfterViewInit() 中访问 ViewChild 查询。它在 ngOnInit() 中不可用,因此您无法定义。
推荐阅读
- python - 检索条目的输入值 - Tkinter
- java - 如何在 jigsaw 和 jre 8 支持下使用 maven?
- azure - 无法从 Kubernetes 获取 apiVersions:无法检索服务器 API 的完整列表
- function - 这个玩具语言伪代码的编译版本将如何在汇编中大致工作?
- c - emcc 无法在 Mac OSX 10.15、clang-10 上运行:错误未知参数:'-fignore-exceptions'
- javascript - 更改 node_args 后 Pm2 重启 Node.js 进程
- twitter-bootstrap - 如何从 Thymeleaf 中的变量显示引导工具提示标题?
- docker - 可以在单个主机上运行多个 squid 容器吗?
- php - 如何在 Laravel 每个循环之外保存值
- json - 如何使用 jq 将对象添加到现有的 json 文件