angular 中 getElementsByTagName 的等价物
Equivalent of getElementsByTagName in angular
我正在尝试 select 全部 textarea
在一个网页中。
有没有一种方法可以在一个查询中获取所有这些元素并循环遍历它们,以便在我添加文本时使用 Renderer2 renderer.listen
in order to implement a 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>
我正在尝试 select 全部 textarea
在一个网页中。
有没有一种方法可以在一个查询中获取所有这些元素并循环遍历它们,以便在我添加文本时使用 Renderer2 renderer.listen
in order to implement a 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>