'Blazor [Parameter] not update using @ref

I'm using .net6.0 Blazor razor library to create a component.

@using Microsoft.JSInterop;
@inject IJSRuntime _jsRuntime;

<audio id="@Id" src="@Source" />

@code {
    [Parameter]
    public string Id { get; set; }

    [Parameter]
    public string Source { get; set; }
}

I use this component in a razor page using this :

<AudioPlayer     
    Id="reactorAudioElement1"
    Source="/audio/lion-roaring.ogg">
</AudioPlayer>

And everything is doing fine at this point.

But, if I try to use @ref like that,

<AudioPlayer 
    @ref=@_Jukebox2>
</AudioPlayer>
@code {
    private AudioPlayer _Jukebox2;
    protected override void OnInitialized()
    {
        _Jukebox2 = new AudioPlayer()
        {
            Id="reactorAudioElement2",
            Source="/audio/Bleep_02.ogg"
        };
    }
}

nothing is set in the DOM.

But I can read data like this, and I cannot set it...

<AudioPlayer 
    @ref=@_Jukebox2
    Id="reactorAudioElement2"
</AudioPlayer>
@code {
    private AudioPlayer _Jukebox2;
    protected override void OnAfterRender(bool firstRender)
    {
        Console.WriteLine(_Jukebox2.Id); //ok
        _Jukebox2.Source = "toto.mp3"; //doesn't do anything
    }
}

Adding a StateHasChanged(); is not working

What am I doing wrong ?



Solution 1:[1]

Your component in DOM is created with this section of code, and your component will have valid @ref value

<AudioPlayer 
    @ref=@_Jukebox2
    Id="reactorAudioElement2"
</AudioPlayer>

but you are creating another object in code with this section of code

_Jukebox2 = new AudioPlayer()
        {
            Id="reactorAudioElement2",
            Source="/audio/Bleep_02.ogg"
        };

In above code you can create object, but can not have DOM reference

This part of code will create an element in DOM and set it's reference to _Jukebox2, will also set value of Source

 <AudioPlayer 
        @ref=@_Jukebox2
        Id="reactorAudioElement2"
        Source="@source"
    </AudioPlayer>

private string source="Source="/audio/Bleep_02.ogg"`;

And in code behind you should be able to access public methods or variable in _Jukebox2 like this

_Jukebox.Source="toto.mp3";

If its not updating DOM then issue might be somewhere else

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1