发布于 1年前

Angular 4选择组件模板DOM元素(DOM操作)的方式

Angular提供了多种方式让我们获取页面的元素。主要分为两种:

  • 基于Decorator:@ViewChild,@ViewChildren,@ContentChild,@ContentChildren
  • 使用ElementRef以及querySelector

Decorator:@ViewChild,@ViewChildren,@ContentChild,@ContentChildren

@ViewChild

获取页面匹配到第一个元素或者指令

页面

<input #myname>

使用

@Component({selector: 'myCmp', templateUrl: 'myCmp.html'})
class MyCmp implements AfterViewInit {
  @ViewChild('myname') input;

  ngAfterViewInit() {
    // do something
  }
}

匹配指令

import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core';

@Directive({selector: 'child-directive'})
class ChildDirective {
}

@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
 @ViewChild(ChildDirective) child: ChildDirective;

 ngAfterViewInit() {
  // do something
 }
}

@ViewChildren

和@ViewChild类似,匹配多个页面元素或指令,返回一个QueryList

@Directive({selector: 'child-directive'})
class ChildDirective {
}

@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
 @ViewChildren(ChildDirective) viewChildren: QueryList<ChildDirective>;

 ngAfterViewInit() {
  // viewChildren is set
 }
}

对于多个元素可以使用逗号隔开,注意不支持有空格,@ViewChildren("var1,var2,var3")

我们可以在ngOnInit里订阅@ViewChild或@ViewChildren里元素的更新:

@ViewChildren(SomeType) viewChildren;

ngOnInit() {
  this.viewChildren.changes.subscribe(changes => console.log(changes));
  this.contentChildren.changes.subscribe(changes => console.log(changes));
}

@ContentChild和@ContentChildren:它们类似于@ViewChild和@ViewChildren,只是它们针对的是<ng-content>。

ElementRef

处理使用@ViewChild,@ViewChildren,@ContentChild和@ContentChildren外,我们也可以在组件的构造器注入ElementRef,使用ElementRef内置nativeElement的querySelector获取DOM节点。

export class MyComponent implements AfterViewInit{
  constructor(private elRef:ElementRef) {}
  ngAfterViewInit() {
    var div = this.elRef.nativeElement.querySelector('div');
    console.log(div);
  }
}
©2020 edoou.com   京ICP备16001874号-3