2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > angular——获取 DOM 元素

angular——获取 DOM 元素

时间:2021-11-10 16:52:24

相关推荐

angular——获取 DOM 元素

当需要获取当前组件模版里的某一个元素时

@ViewChild配合local template variable

原生元素可以通过local variable获取。在写组件时,我们可以直接在组件模版里给这个 input 标签加标记(譬如:#myInput), 然后把标记传给@ViewChild用来获取该元素。当组件初始化后,你就可以通过 renderer 在这个 input 标签上执行 focus 方法了。

@ViewChild配合local variable(推荐)

@Component({selector: 'my-comp',template: `<input #myInput type="text" /><div> Some other content </div>`})export class MyComp implements AfterViewInit {@ViewChild('myInput') input: ElementRef;constructor(private renderer: Renderer) {}ngAfterViewInit() {this.renderer.invokeElementMethod(this.input.nativeElement, 'focus');}}

当需要获取用户映射到组件里的某个元素时

@ContentChildren配合 li 选择器指令

介绍一个好方案,用@Directive装饰器,配合他的 selector 功能。定义一个能查找/选择<li>元素的指令,然后用@ContentChildren过滤用户映射进当前组件里的内容,只留下符合条件的 li 元素。

@ContentChildren配合@Directive(推荐)

// user code<my-list><li *ngFor="#item of items"> {{item}} </li></my-list>@Directive({selector: 'li' })export class ListItem {}// component code@Component({selector: 'my-list'})export class MyList implements AfterContentInit {@ContentChildren(ListItem) items: QueryList<ListItem>;ngAfterContentInit() {// do something with list items}}

原文查看

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。