[英]Angular 5 (& more): HTMLElement with @ViewChild
I have to reference an htmlElement
with a @ViewChild()
, is there any way to this?我必须用
@ViewChild()
引用htmlElement
,有什么办法吗? I have to create an HTMLElement and then try to assign a reference to a viewChild
or something similar.我必须创建一个 HTMLElement,然后尝试将引用分配给
viewChild
或类似的东西。 THank you for your attention.感谢您的关注。
It's not so simple. 这不是那么简单。 ViewChild should be used for:
ViewChild应该用于:
any class with the Component or Directive decorator 任何带有Component或Directive装饰器的类
a template reference variable as a string (eg query with ViewChild('cmp')) 模板引用变量作为字符串(例如,使用ViewChild('cmp')查询)
any provider defined in the child component tree of the current component (eg ViewChild(SomeService) someService: SomeService) 当前组件的子组件树中定义的任何提供程序(例如ViewChild(SomeService)someService:SomeService)
any provider defined through a string token (eg ViewChild('someToken') someTokenVal: any) 通过字符串令牌定义的任何提供程序(例如ViewChild('someToken')someTokenVal:any)
a TemplateRef (eg query with ViewChild(TemplateRef) template;) TemplateRef(例如,使用ViewChild(TemplateRef)模板进行查询;)
In your case better to use last option: 在您的情况下,最好使用最后一个选项:
<input #testInput >
TS: TS:
...
@ViewChild('testInput') input;
...
I came here looking for a way to get the HTMLElement
from a ViewChild
that's selecting a child component.我来这里是为了寻找一种从选择子组件的
ViewChild
中获取HTMLElement
的方法。 I realize that this is not exactly what the question is about.我意识到这并不是问题的真正含义。 Still, it might be helpful.
不过,它可能会有所帮助。
This can be achived using the read
option inside the ViewChild.opts
:这可以使用
ViewChild.opts
的read
选项来ViewChild.opts
:
<my-child-component #mySelector></my-child-component>
@ViewChild('mySelector', {read: ElementRef})
childElement: ElementRef<HTMLElement>;
doSomething() {
const htmlElement = childElement.nativeElement;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.