Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - 通过ID获取元素-Angular2(Get element by id - Angular2)

I have a code:(我有一个代码:)

document.getElementById('loginInput').value = '123';

But while compiling the code I receive following error:(但是在编译代码时,我收到以下错误:)

Property value does not exist on type HTMLElement.(属性值在HTMLElement类型上不存在。)

I have declared a var: value: string;(我已经声明了var: value: string;)

.(。)

How can I avoid this error?(如何避免此错误?)

Thank you.(谢谢。)

  ask by Natalia translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you want to set value than you can do the same in some function on click or on some event fire.(如果要设置值,则可以在单击或某些事件触发时在某些功能中执行相同的操作。)

also you can get value using ViewChild using local variable like this(你也可以像这样使用局部变量使用ViewChild获得价值)

<input type='text' id='loginInput' #abc/>

and get value like this(并得到这样的价值)

this.abc.nativeElement.value

here is working example(这是工作示例)

Update(更新资料)

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this(好的,您必须像这样使用ngAfterViewInit方法)

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading(ngAfterViewInit将不会引发任何错误,因为它将在模板加载后呈现)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...