【发布时间】:2017-01-30 14:12:17
【问题描述】:
<div>
<input #ipt type="text"/>
</div>
是否可以从组件类中访问模板访问变量?
也就是说,我可以在这里访问它吗,
class XComponent{
somefunction(){
//Can I access #ipt here?
}
}
【问题讨论】:
标签: angular typescript angular2-template
<div>
<input #ipt type="text"/>
</div>
是否可以从组件类中访问模板访问变量?
也就是说,我可以在这里访问它吗,
class XComponent{
somefunction(){
//Can I access #ipt here?
}
}
【问题讨论】:
标签: angular typescript angular2-template
@ViewChild('modal reference variable', { static: true }) name: ElementRef;
有时它不适用于模态。所以当我在 Angular 中使用模态时会出错,所以我使用它。
@ViewChild('modal reference variable', { static: true }) name!: ElementRef;
如果您希望在不单击按钮的情况下执行模式,它肯定会起作用。
【讨论】:
这是@ViewChild 的一个用例:
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
class XComponent {
@ViewChild('ipt', { static: true }) input: ElementRef;
ngAfterViewInit() {
// this.input is NOW valid !!
}
somefunction() {
this.input.nativeElement......
}
}
这是一个工作演示:
https://stackblitz.com/edit/angular-viewchilddemo?file=src%2Fapp%2Fapp.component.ts
【讨论】:
ngAfterViewInit() 被触发后可用。你必须从 '@angular/core` 导入ViewChild ..
this.ipt.nativeElement.setAttribute('value', 'xxx'); 但没有任何反应。并且没有像 value() 或 setValue() 这样的方法,即使我声明它的类型为 HTMLInputElement(我基于 IDE 的代码提示/自动完成)。就我而言,我不在乎阅读价值。我只需要设置不同的值。
setProperty 吗?
this.input.nativeElement.value = 'test' 工作吗?!也许表单及其绑定存在特殊行为。