Lifecycle and DOM
Accessing DOM Elements
Accessing DOM elements lets you obtain a direct reference to a rendered node so you can read from it or interact with it from the component.
Example
Focusing a text input when a button is clicked.
VueuseTemplateRef
<script setup lang="ts">
import { useTemplateRef } from 'vue'
const inputRef = useTemplateRef<HTMLInputElement>('inputRef')
function focusInput() {
inputRef.value?.focus()
}
</script>
<template>
<input ref="inputRef" type="text" />
<button @click="focusInput">
Focus input
</button>
</template>
It uses template refs to obtain a direct reference to a DOM element after it renders.
ReactuseRef
import { useRef } from 'react'
function InputFocus() {
const inputRef = useRef<HTMLInputElement | null>(null)
function focusInput() {
inputRef.current?.focus()
}
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>
Focus input
</button>
</>
)
}
It uses useRef to store a mutable reference to the DOM node and access it from handlers or effects.
AngularviewChild()
import { Component, ElementRef, viewChild } from '@angular/core'
@Component({
selector: 'app-input-focus',
standalone: true,
template: `
<input #inputRef type="text" />
<button (click)="focusInput()">
Focus input
</button>
`,
})
export class InputFocusComponent {
inputRef = viewChild.required<ElementRef<HTMLInputElement>>('inputRef')
focusInput() {
this.inputRef().nativeElement.focus()
}
}
It uses viewChild() to query a template element and access its ElementRef from the component.
