viewChild query returns Signal<ElementRef> instead of Signal<Element>

Discussão em 'Angular' iniciado por ka_fuachie, Janeiro 29, 2025.

  1. ka_fuachie

    ka_fuachie Guest

    I'm using viewChild to get reference to some element, I expect the signal to return a reference to the element but it seems to return the old syntax {nativeElement: Element} instead

    Package: @angular/core@19.1.3

    import {Component, signal, computed, viewChild} from '@angular/core';
    import {bootstrapApplication} from '@angular/platform-browser';

    @Component({
    selector: 'app-root',
    template: `
    <h2>Cookie recipe</h2>

    <label>
    # of cookies:
    <input #input type="range" min="10" max="100" step="10" [value]="count()" (input)="update($event)" />
    {{ count() }}
    </label>

    <p>Butter: {{ butter() }} cup(s)</p>
    <p>Sugar: {{ sugar() }} cup(s)</p>
    <p>Flour: {{ flour() }} cup(s)</p>

    <button
    type="button"
    (click)="log()"
    >Log</button>
    `,
    })
    export class CookieRecipe {
    count = signal(10);
    input = viewChild<HTMLInputElement>("input")

    butter = computed(() => this.count() * 0.1);
    sugar = computed(() => this.count() * 0.05);
    flour = computed(() => this.count() * 0.2);

    update(event: Event) {
    const input = event.target as HTMLInputElement;
    this.count.set(parseInt(input.value));
    }

    log() {
    alert(`input: ${this.input()?.nativeElement.value}`) // Works but typescript complains
    alert(`input: ${this.input()?.value}`) // Doesn't work but fine with typescript
    }
    }

    bootstrapApplication(CookieRecipe);

    Continue reading...

Compartilhe esta Página