Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set page title in blazor?

Tags:

blazor

As Blazor being a SPA framework, I would like to know is it possible to set a page title for each individual page in Blazor?

I am currently working on Blazor webassembly project and cannot figure out a way how to add a page title since there is only one index.html as it should be in SPA, but would be really useful if it can be achieved to set title for each "page".

like image 351
mko Avatar asked Nov 14 '19 18:11

mko


People also ask

How do I change page title in Blazor?

Blazor doesn't provide any built-in method to change the page title. This means you need to call a JS function to update the document title. The page title is updated when you set the Title parameter.

How can I get page name in Blazor?

You can get the current page title in Blazor by using the “title” property of the document object in JavaScript and by using a . JavaScript interop since there is no DOM accessibility in Blazor.


Video Answer


2 Answers

Note: starting with .Net 6.0 there is official support for changing the title, so the solution below is no longer needed.

  1. Provide following script in your index.html (or in an included .js file):

    <script>
         setTitle = (title) => { document.title = title; };
    </script>
    
  1. In each page inject the jsinterop:

    @inject IJSRuntime JSRuntime;
    
  2. After each render, set the document title to the value of your choice:

    @code
    {
       protected override async Task OnAfterRenderAsync(bool firstRender)
       {
          await JSRuntime.InvokeVoidAsync("setTitle", "this is the new title"); ;        
       }    
    }
    
like image 97
Johan Donne Avatar answered Oct 09 '22 12:10

Johan Donne


In ASP.NET CORE 5.0, a new component for Title is added

 <Title value="Page title" /> 

Msdn Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/additional-scenarios?view=aspnetcore-5.0#influence-html-head-tag-elements

First add the using statement in the component

@using Microsoft.AspNetCore.Components.Web.Extensions.Head

You can install (if not installed) using the command.

dotnet add package Microsoft.AspNetCore.Components.Web.Extensions --version 5.0.0-preview9.20467.1

5.0.0-preview9.20467.1 is the version when I am writing this. Please check the nuget url for the latest version

Nuget url: https://www.nuget.org/packages/Microsoft.AspNetCore.Components.Web.Extensions/

Then add the Title tag.

<Title Value="My page title" />

See the sample output image below

enter image description here

like image 20
Bibin Gangadharan Avatar answered Oct 09 '22 13:10

Bibin Gangadharan