像javascript中的document.getElementById(“ id”),我们可以在angular2及更高版本中执行以在类型脚本中获取dom元素的操作

问题描述 投票:0回答:1

像javascript中的document.getElementById(“ id”),我们可以在angular2及更高版本中做什么以在类型脚本中获取dom元素?

我尝试了angular.element但它不起作用

angular
1个回答
0
投票

有多种方法可以做到这一点。我将展示其中之一。

  1. 您可以使用它。

    • document.querySelectorAll('。class-name')
    • document.querySelectorAll('#idname')
    • document.querySelectorAll('#tagname')

工作示例在这里

https://stackblitz.com/edit/angular-n8gau2

  1. 您也可以使用@viewChild

Component.ts

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

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';


  @ViewChild('pRef', {static: false}) pRef: ElementRef;

    ngAfterViewInit() {
    console.log(this.pRef.nativeElement.innerHTML); 
    this.pRef.nativeElement.innerHTML = "DOM updated succesfully!!!"; 
  }
}

。html

<hello name="{{ name }}" ></hello>

<p #pRef>
  Start editing to see some magic happen :)
</p>

工作示例在这里

https://stackblitz.com/edit/angular-8-viewchild-example

© www.soinside.com 2019 - 2024. All rights reserved.