One of the first things I found with Blazor was no ability to set the page title.
This may come natively in time, but for now here is a simple solution.
Firstly, we need to define some JavaScript - you can put this directly in your index.html
as a script
or in a JS library file. (Ideally the build pipeline would compile all component JS into a single minified file and attach it to the index.html
automatically. One day.)
window.setTitle = (title) => {
console.log('Setting title', title);
document.title = title;
}
This simply creates a function in the window
scope that sets the title to whatever is in the input.
Then we create a PageTitle.razor component to use in other components to manage the page title:
@inject IJSRuntime JSRuntime;
@code {
private String _title = "";
[Parameter]
public String Title {
get {
return this._title;
}
set {
this._title = value;
setTitle();
}
}
protected override void OnInitialized() {
setTitle();
}
private void setTitle() {
System.Console.WriteLine("Blazor setting Title to {0}", this._title);
JSRuntime.InvokeAsync<string>("setTitle", new object[] { this._title });
}
}
We inject the JSRuntime
to allow interop with JavaScript. The Title
property has a simple getter, but the setter is designed to trigger a refresh in the code below.
To use the component in another (I'm using the Counter example), it is used as normal:
<PageTitle Title="Counter" @ref="PageTitle" />
This will change the page title to Counter when the component is initialised. I've added a reference so that I can use the code below:
private PageTitle PageTitle;
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
this.PageTitle.Title = String.Format("Counter: {0}", currentCount);
Console.WriteLine("Incrementing");
AlertService.addMessage(new Alert(currentCount.ToString(), Alerts.Info));
}
The reference to PageTitle
is created to allow it to be used and wired up to the component specified above by Blazor's default magic.
Then after incrementing the counter, we set the Title
to the formatted string. You will remember above that the setter has logic to trigger the refresh when the title is changed.
(My AlertService)
This works fine (albeit with a tiny delay, but nothing a user will notice). You will get a build warning:
Pages\Counter.razor(18,9): warning BL0005: Component parameter 'Title' should not be set outside of its component. [C:\code\blazor\first-run\WebApplication1\WebApplication1.csproj]
This could be eradicated by using a method instead of setter, but I wanted to show this way of doing it.
Top comments (0)