source

document.getElementById를 angular4 / typscript로 대체하시겠습니까?

myloves 2023. 3. 19. 19:37

document.getElementById를 angular4 / typscript로 대체하시겠습니까?

연습할 때 angular4랑 같이 작업하고 있는데 저는 처음이에요.

HTML 요소와 그 값을 얻기 위해<HTMLInputElement> document.getElementById또는<HTMLSelectElement> document.getElementById.

앵귤러로 대체할 수 있는 것이 있는지 궁금합니다.

다음을 사용하여 DOM 요소에 태그를 지정할 수 있습니다.#someTag를 사용하여 입수할 수 있습니다.@ViewChild('someTag').

완전한 예를 참조해 주세요.

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

@Component({
    selector: 'app',
    template: `
        <div #myDiv>Some text</div>
    `,
})
export class AppComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    }
}

console.log일부 텍스트를 인쇄합니다.

DOCUMENT 토큰을 생성자에 주입하고 동일한 함수를 사용할 수 있습니다.

import { Inject }  from '@angular/core';
import { DOCUMENT } from '@angular/common'; 

@Component({...})
export class AppCmp {
   constructor(@Inject(DOCUMENT) document: Document) {
      document.getElementById('el');
   }
}

또는 가져올 요소가 해당 구성 요소에 있는 경우 템플릿 참조사용할 수 있습니다.

Angular 8 또는 postor @ViewChild의 경우 opts라는 추가 파라미터가 있으며 read와 static의 두 가지 속성이 있습니다.read는 옵션입니다.다음과 같이 사용할 수 있습니다.

import { ElementRef, ViewChild } from '@angular/core';
// ...
@ViewChild('mydiv', { static: false }) public mydiv: ElementRef;

constructor() {
// ...
<div #mydiv></div>

메모: Angular 9에서는 Static: false는 필요 없습니다.(그냥){ static: true }ngOnInit 내의 변수를 사용하는 경우)

이것을 시험해 보세요.

TypeScript 파일 코드:

(<HTMLInputElement> document.getElementById("name")).값

HTML 코드:

<input id="name" type="text" #name />
  element: HTMLElement;

  constructor() {}

  fakeClick(){
    this.element = document.getElementById('ButtonX') as HTMLElement;
    this.element.click();
  }

언급URL : https://stackoverflow.com/questions/48226868/document-getelementbyid-replacement-in-angular4-typescript