Reputation: 595
I am referencing an <h1>
with ref="header"
. I'm trying to change CSS rules but a TypeScript error is not letting me.
const header = ref<HTMLElement | null>(null)
onMounted(() => {
header.value.style.color = "red"
})
Upvotes: 0
Views: 1121
Reputation: 2790
The error is perfectly reasonable: you can't be sure that that element exists.
And if the element doesn't exist, the template ref's value will be null
.
It's actually right there in the type for the ref: HTMLElement | null
.
You can change your onMounted
callback to the following to check for that:
onMounted(() => {
if (header.value)
header.value.style.color = "red"
})
Upvotes: 2