This blog post will show you how to reference components in another component. To make the demo simple, I have created a simple contact list. Then from the parent page, I am referring to the contact list and invoking the show/hide method of the contact list.
BlazorApp/Models/Contact.cs
namespace BlazorApp.Models
{
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
}
}
Create a razor component named ContactList and paste the following code
BlazorApp/Page/ContactList.razor
@using Models
<h4>Contact List</h4>
<table hidden="@showContacts">
<thead>
<th>Name</th>
<th>Email</th>
</thead>
<tbody>
@foreach (var item in contacts!)
{
<tr>
<td>@item.Name</td>
<td>@item.Email</td>
</tr>
}
</tbody>
</table>
@code {
private bool showContacts = true;
private List<Contact>? contacts = null;
protected override void OnInitialized()
{
contacts = new List<Contact>(){
new Contact(){Name="John ",Email="john@example.com"},
new Contact(){Name="Bob",Email="bob@example.com"},
new Contact(){Name="Bill",Email="bill@example.com"}
};
base.OnInitialized();
}
public void ShowContacts(){
showContacts=true;
StateHasChanged();
}
public void HideContacts(){
showContacts=false;
StateHasChanged();
}
}
The above component shows the contact list and has two public methods, ShowContacts
and HideContacts
Which we will trigger from the Parent component.
Now in Index.razor page paste the following code
BlazorApp/Page/Index.razor
@page "/"
<PageTitle>Index</PageTitle>
<ContactList @ref="contactListRef" ></ContactList>
<button @onclick="ShowHide">Show/Hide</button>
@code{
private bool isContactVisisble=true;
private ContactList contactListRef;
public void ShowHide(){
isContactVisisble=!isContactVisisble;
if(!isContactVisisble){
contactListRef.HideContacts();
}else{
contactListRef.ShowContacts();
}
}
}
In the above code, I have declared a private variable contactListRef
private ContactList contactListRef;
and then I have assigned it to the @ref attribute
<ContactList @ref="contactListRef" ></ContactList>
What is @ref
As per the MSDN. Component references provide a way to reference a component instance for issuing commands. To capture a component reference:
- Add an
@ref
attribute to the child component. - Define a field with the same type as the child component.
- The field is populated with the component instance when the component is rendered. You can then invoke .NET methods on the instance.
index.razor
the page has one button; on the click of a button, I am invoking the reference component method, which shows and hides the component
public void ShowHide(){
isContactVisisble=!isContactVisisble;
if(!isContactVisisble){
contactListRef.HideContacts();
}else{
contactListRef.ShowContacts();
}
}