Understanding Parameters
Parameters in Blazor are used to pass data from a parent component to a child component. They are defined using public properties on a component and decorated with the [Parameter] attribute.
Non-Complex Objects
Non-complex objects such as integers, strings, and booleans can be passed as parameters. Here’s an example:
@page "/example"
<ChildComponent Title="Hello, World!" />
In this example, the Title parameter is a non-complex object (a string), and we’re passing the value “Hello, World!” to it.
Complex Objects
Complex objects such as lists, custom classes, or arrays can also be passed as parameters. Here’s an example:
@page "/example"
<ChildComponent Employee="Employee" />
@code {
public Employee Employee { get; set; }
protected override void OnInitialized()
{
Employee = new Employee { Id = 1, Name = "John Doe", Role = "Developer" };
}
}
In this example, Employee is a complex object. We’re creating a new Employee object and passing it as a parameter to the ChildComponent.
ChildComponent with Non-Complex Parameter
Here’s the code for a ChildComponent that accepts a non-complex parameter:
<h1>@Title</h1>
@code {
[Parameter]
public string Title { get; set; }
}
In this component, Title is a parameter that you can pass a string value to.
ChildComponent with Complex Parameter
Here’s the code for a ChildComponent that accepts a complex parameter:
<h1>@Employee.Name</h1>
<h2>@Employee.Role</h2>
@code {
[Parameter]
public Employee Employee { get; set; }
}
In this component, Employee is a parameter that you can pass an Employee object to. The Employee class might look something like this:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Role { get; set; }
}
Conclusion
Blazor components and parameters are fundamental concepts in Blazor applications. Understanding how to use them is crucial for building interactive and dynamic web UIs. Whether you’re passing simple integers or complex objects, Blazor provides the flexibility and power you need to build your applications.
I hope this helps! Let me know if you have any questions or need further clarification on any points. Happy coding!
C est bien fait