Baslki
Baslki

Reputation: 63

Blazor C#: Pass parameter from child component to parent component

In a blazor C# app, I have a page called TopicVideo.razor with the following code:

<div id="video-input">
        <input @bind="YouTubeVideoUrl" type="text" placeholder="Video URL" style="max-height: 30px;">
        <button class="summarizeBtn" @onclick="InitiateYouTubeDownload" tabindex="5">OK</button>
    </div>
</div>

@code {

private async Task InitiateYouTubeDownload(){ 
// process

}

I wanted to create a new component called OptionOne.razor, that replaces the div with id "video-input" in the page TopicVideo.razor. So I created this:

<div id="video-input">
      <input @bind="YouTubeVideoUrl" type="text" placeholder="Video URL">
      <button @onclick="InitiateYouTubeDownload" tabindex="5">OK</button>
  </div>


@code {
    [Parameter] public string? YouTubeVideoUrl { get; set; }
    [Parameter] public EventCallback<MouseEventArgs> InitiateYouTubeDownload { get; set; }
}

and in TopicVideo, I replaced the div with id "video-input" with the following:

<OptionOne YouTubeVideoUrl="YouTubeVideoUrl" InitiateYouTubeDownload="InitiateYouTubeDownload"></OptionOne>

Issue is: It seems the OptionOne component is not passing YouTubeVideoUrl correctly. When I use the VS Code Debugger, hovering over YouTubeVideoUrl in the OptionOne page shows the correct URL, but hovering over it in the TopicVideo.razor page shows "null". How do I pass YouTubeVideoUrl from the child component OptionOne to the parent component TopicVideo?

Upvotes: 1

Views: 2501

Answers (1)

Lex
Lex

Reputation: 7194

Since you already have an event registered, you can just use that to pass the URL of the video back to the parent. You could make the following changes:

OptionOne.razor:

<div id="video-input">
      <input @bind="this.YouTubeVideoUrl" type="text" placeholder="Video URL">
      <button @onclick="this.StartYouTubeDownload" tabindex="5">OK</button>
  </div>


@code {
    [Parameter] public string? YouTubeVideoUrl { get; set; }
    [Parameter] public EventCallback<string> InitiateYouTubeDownload { get; set; }

    private async Task StartYouTubeDownload() 
    {
        if (this.InitiateYouTubeDownload.HasDelegate)
        {
            await this.InitiateYouTubeDownload.InvokeAsync(this.YouTubeVideoUrl);
        }
    }
}

TopicVideo.razor:

<OptionOne YouTubeVideoUrl="@this.YouTubeVideoUrl" InitiateYouTubeDownload="this.InitiateYouTubeDownload"></OptionOne>

@code {
    private string YouTubeVideoUrl;

    private void InitiateYouTubeDownload(string url)
    {
        this.YouTubeVideoUrl = url;
    }
}

Upvotes: 3

Related Questions