0
点赞
收藏
分享

微信扫一扫

Angular 获取页面dom元素

如何在ts里操作页面元素

构造函数依赖注入ElementRef

constructor( private elementRef: ElementRef) {
 //不能在此处获取元素,因为页面还没渲染
 }
 ngOnInit() {
  //在初始化的时候处理
  this.elRef.nativeElement.querySelector('mat-select') as any).focus();
}

属性装饰符 @ViewChild

html

<div class="box" [innerHTML]="content | translate" #box></div>

ts
获取页面元素

@ViewChild('box') box: ElementRef;
constructor(private renderer: Renderer2) {
  }
ngAfterViewInit() {
  //设置样式
    this.renderer.setStyle(this.box.nativeElement, 'backgground', 'red');
}
举报

相关推荐

0 条评论