2017-03-18 88 views
0

我是初学者角2返回null使用document.getelement通过ID

这里是我的输入

<input type="hidden" value={{date}} #myname/> 

这里是我的代码

console.log(document.getElementById('myname'));它返回null

为什么呢?

请告知我,

感谢

+0

如果您正在使用角CLI。你可以添加jquery到你的配置文件,并用它来代替文档。像$('#myname') –

+0

任何其他方式来解决这个问题... :( – Anivaishu

+0

可能重复的[角2/typescript:获取模板中的元素](http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-an-of-the-template) – Alex

回答

1

当你定义模板变量,您可以访问使用ViewChild装饰该元素。 document.getElementById只有在id属性中具有id属性时才会起作用。

@ViewChild('myname') myNameElem: any; 
+0

谢谢你的答复。我用这个但是我的安慰值是undefined.Aualually这是我的代码, ViewChild('myname')myNameElem:any;和console.log(this.myNameElem); – Anivaishu

+0

@Anivaishu你可以请更新你的问题到目前为止你已经尝试过.. –

+0

我需要得到输入元素value.I试着很多way.But不wrk。 – Anivaishu

0
import {ElementRef} from '@angular/core'; 

@ViewChild('myname') el:ElementRef; 

ngAfterViewInit() 
{ 
    //this.el.nativeElement.focus(); 
    //this.el.nativeElement.value() 
    // And more 

} 
+0

我试过这但我我得到这个错误nativeE lement is undefined – Anivaishu

+0

http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 –