Nat*_*lia 39 javascript typescript angular
我有一个代码:
document.getElementById('loginInput').value = '123';
Run Code Online (Sandbox Code Playgroud)
但在编译代码时我收到以下错误:
HTMLElement类型中不存在属性值.
我宣布了一个var : value: string;.
我怎样才能避免这个错误?
谢谢.
Par*_*ain 34
如果你想设置值,你可以在点击或某些事件触发的某些功能中做同样的事情.
你也可以使用ViewChild像这样的局部变量来获得价值
<input type='text' id='loginInput' #abc/>
Run Code Online (Sandbox Code Playgroud)
并获得这样的价值
this.abc.nativeElement.value
Run Code Online (Sandbox Code Playgroud)
好吧,你必须使用ngAfterViewInitangualr2的方法,就像这样
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
Run Code Online (Sandbox Code Playgroud)
ngAfterViewInit不会抛出任何错误,因为它将在模板加载后呈现
Gop*_*ine 17
(<HTMLInputElement>document.getElementById('loginInput')).value = '123';
Run Code Online (Sandbox Code Playgroud)
Angular不能直接获取html元素,你需要通过将上面的泛型绑定到它来指定元素类型.
一种不同的方法,即:你可以做到'Angular方式'并使用ngModel和document.getElementById('loginInput').value = '123';完全跳过.代替:
<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>
Run Code Online (Sandbox Code Playgroud)
并在您的组件中提供以下值:
username: 'whatever'
password: 'whatever'
Run Code Online (Sandbox Code Playgroud)
这将在导航到页面时预设用户名和密码.
| 归档时间: |
|
| 查看次数: |
108749 次 |
| 最近记录: |