我试图在一个网页中选择所有 textarea
。
有没有一种方法可以在一个查询中获取所有这些元素并循环遍历它们以使用 Renderer2 为每个元素添加一个监听器? renderer.listen
为了实现 vertical auto expand of the textarea
每当我添加文本时。
如果我使用@viewchild,我必须为它们中的每一个手动添加不同的模板引用变量。
is it possible to have something similar to getElementsByTagName in angular and avoid direct access to DOM ?
最佳答案
指令非常适合您的场景。
这不是最终的实现,但应该会让您对如何使用它有一个很好的了解。
import { Directive } from '@angular/core';
@Directive({
selector: 'textarea[resize]'
})
export class HighlightDirective {
@HostBinding('style.height.px')
height: number;
@HostListener('change')
@HostListener('cut')
@HostListener('paste')
@HostListener('drop')
@HostListener('keydown')
onClicked(event: Event) {
this.resize();
}
constructor(private elementRef: ElementRef) {}
resize() {
const textArea = this.elementRef.nativeElement as HTMLTextAreaElement;
this.height = textArea.scrollHeight;
}
}
在你的模板中装饰你的textarea
:
<textarea resize></textarea>
关于angular - 等价于 getElementsByTagName 的 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233234/