How to set page title in blazor?
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
For those targeting .NET Core 3.1
Kudos to this post, you can make a reusable component.
Add below script to a js file, or add to index.html
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<script>
window.setTitle = (title) => {
document.title = title;
}
</script>
</body>
</html>
In the shared folder create a new component PageTitle.razor
@inject IJSRuntime JsRuntime;
@code {
[Parameter]
public string Title { get; set; }
protected override async Task OnInitializedAsync()
{
await SetTitle();
}
private async Task SetTitle()
{
await JsRuntime.InvokeVoidAsync("setTitle", Title);
}
}
Add to the razor page you want to change the name of:
<PageTitle Title="Home sweet home" />
Note: starting with .Net 6.0 there is official support for changing the title, so the solution below is no longer needed.
Provide following script in your index.html (or in an included .js file):
<script> setTitle = (title) => { document.title = title; }; </script>
In each page inject the jsinterop:
@inject IJSRuntime JSRuntime;
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"); ; } }
From ASP.NET CORE 6.0
, the official docs says that we can Influence HTML <title>
tag elements easily by using PageTitle
component.
Add the HeadOutlet
Component in Program.cs
builder.RootComponents.Add<HeadOutlet>("head::after");
Then use PageTitle
Component
<PageTitle>@title</PageTitle>
Update 1:
Looks like this API has been put on hold to improve further. This has been removed from official docs link. Here is the github issue tracking the same. I'll update the answer once the API finally gets available in docs.
Update 2:
The above issue has been resolved and ASP.NET Core
team added <PageTitle>
component in ASP.NET Core 6.0
. I have also updated the answer accordingly.