jsakamoto / Toolbelt.Blazor.HeadElement

Head element support (change the document title, "meta" elements such as OGP, and "link" elements) for Blazor apps.
https://demo-blazor-headelement.azurewebsites.net/
Mozilla Public License 2.0
158 stars 11 forks source link

Unable to render title from within components with OnAfterRenderAsync #19

Closed Xeevis closed 2 years ago

Xeevis commented 3 years ago

Hello. I'm trying to create component that would display current page title. Problem is, it doesn't work when used with OnAfterRenderAsync, probably because it's fired before the title is set as any later call does work.

<h1>@title</h1> @* null *@
@code {
  string title;
  protected override async Task OnAfterRenderAsync(bool firstRender)
  {
    if (firstRender)
    {
      title = await HeadElementHelper.GetTitleAsync();
    }
  }
}

Perhaps event would be of help here? Something like

protected override void OnInitialized()
{
    HeadElementHelper.TitleChanged += OnTitleChanged;    
}

private void OnTitleChanged(object sender, TitleChangedEventArgs args)
{
    title = args.Title;
}

Thoughts?

jsakamoto commented 3 years ago

@Xeevis Thank you for letting me know!

I could reproduce this problem.

I'm going to fix this issue as soon as possible.

Please give me a few days.

jsakamoto commented 3 years ago

@Xeevis I published the new fixed versions just now.

Could you try it out?

Xeevis commented 3 years ago

@jsakamoto Thanks for the update, however not the problem I have, sorry if I haven't communicated it clearly. My problem is, that I'm trying to render title from a completely different component than the one setting it and that issue is still present for me. If Title component is declared on page Counter.razor, how to display current page title in say Navbar.razor which is child component of MainLayout.razor? This should ideally work with prerendering too.

jsakamoto commented 3 years ago

@Xeevis Why don't you place the only one <Title> component in the Navbar.razor if the Navbar.razor knows what the current page title should be?

Anyway, OnAfterRender and OnAfterRenderAsync are too late to affect the rendering result of server-side prerendering. That is not a limitation of this library. That is by design and by the architecture of Blazor.