I have a modal component in Blazor that I am attempting to make more reusable. The modal has a base class which implements methods for Showing/Hiding the modal, and callbacks for Show and Hide.
public class Modalbase : ComponentBase
{
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public Action? Closed { get; set; }
[Parameter] public Action? Opened { get; set; }
protected bool show;
// ANCHOR - public methods
public void Hide()
{
show = false;
Closed?.Invoke();
this.StateHasChanged();
}
public void Show()
{
show = true;
Opened?.Invoke();
this.StateHasChanged();
}
}
For the razor implementation, I have a very simple component which provides the markup and renders content provided. This is in Modal.razor:
#inherits Modalbase
#if (this.show)
{
<div class='modal-container #(this.show ? "show" : "hidden")'>
<div class="overlay" #onclick="Hide" style="cursor:pointer;"></div>
<div class='modal'>
<div id="close-container" #onclick="Hide">
<div class="close"><i class="fa-solid fa-x fa-md"></i></div>
</div>
#this.ChildContent
</div>
</div>
}
which is then used like this:
<Modal #ref="modalRef">
<div>childcontent here</div>
</Modal>
#code {
Modal modalRef;
public void Show()
{
modalRef.Show();
}
}
The problem with this is that across many implementations of Modals, I have to keep implementing the Show and Hide methods. Those methods are on the Modal component reference, and not in the reference to the implementation of Modal.
Is there a way with OOP to have these methods available directly on the implementation of the Modal component, but also allow them to be overriden if something additional needs to be done before opening/closing the modal?
A workaround is just making modalRef public in implementations, and calling the methods directly from there. Like: childModal.modalRef.Show() But that feels like it could cause issues in cases where maybe I want to check if the user is logged in before showing the modal.
Related
I have a base component PetTemplate and a second PetDog that inherits and uses the template of PetTemplate. PetTemplate has a method named ToggleDisplay. My goal is when I click the button on the Index page that invokes the PetDog.ToggleDisplay method and show/hide the PetDog details on the page.
The "Inside" button in the sample code below works but "Outside" button don't. How can I invoke the ToggleDisplay method from a page or a parent component correctly?
Index.razor
#page "/"
<button #onclick="ShowPetDetails">Show Details (Outside)</button>
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.ToggleDisplay();
}
}
PetDog.razor
#inherits PetTemplate
<PetTemplate Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
PetTemplate.razor
<div class="mt-3">
<button #onclick="ToggleDisplay">Show Details (Inside)</button>
<h3>Pet Name: #Name</h3>
<div style="display:#display">
#ChildContent
</div>
</div>
#code {
string display = "none";
[Parameter]
public string Name { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
StateHasChanged();
}
}
When you use
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.ToggleDisplay();
}
}
You actually create a reference to the PetDog component, and then try to call a derived method, dog.ToggleDisplay(), on object you have no reference to ( the instance of the PetTemplate). In order to make it work, you'll have to get a reference to the parent component (PetTemplate), and provide it to the derived component (PetDog), like this:
PetTemplate.razor
<div class="mt-3">
<button #onclick="ToggleDisplay">Show Details (Inside)</button>
<h3>Pet Name: #Name</h3>
<div style="display:#display">
#ChildContent
</div>
</div>
#code {
string display = "none";
string val;
[Parameter]
public string Name { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
InvokeAsync(() => StateHasChanged());
}
}
PetDog.razor
#inherits PetTemplate
<PetTemplate #ref="petTemplate" Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
#code
{
PetTemplate petTemplate;
public PetTemplate PetTemplateProp { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if(firstRender)
{
PetTemplateProp = petTemplate;
}
base.OnAfterRender(firstRender);
}
}
Index.razor
#page "/"
<button #onclick="ShowPetDetails">Show Details (Outside)</button>
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.PetTemplateProp.ToggleDisplay();
}
}
Note: Though Razor components are C# classes, you cannot treat them as normal classes. They behave differently. As for instance, you can't define a variable instance, and set its parameters, etc. outside of the component. At best, you can capture a reference to a component as well as call public methods on the component instance, as is done in the current sample. In short, component objects differ from normal classes.
It's also important to remember that each component is a separate island that can render independently of its parents and children.
But just wondering how can I change a component parameter value from outside of it, that inherited/uses a template. I tried the methods in the documentation or the resources I found, but it didn't work for my case
You should not (it was a warning) and probably cannot ( it may be now an error) change a component parameter's value outside of the component. As for instance, you can't capture a reference to a component and assign a value to its parameter property:
<PetTemplate #ref="petTemplate">
<div>Someone's best friend!</div>
</PetTemplate>
PetTemplate petTemplate;
This is not allowed: petTemplate.Name="Dog" as this is changing the parameter outside of its component. You can only do that like this:
<PetTemplate Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
Furthermore, modification of a parameter property from within the component itself is deprecated ( currently you should get a warning, at least that is what Steve Sanderson suggested to the Blazor team).
To make it clear, you should not modify the parameter property Name from within the PetTemplate component. A parameter property should be automatic property; that is, having a get and set accessors like this: [Parameter] public string Name { get; set; }
And you should not use it like this:
private string name;
[Parameter]
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
// Code to a method or whatever to do something
}
}
}
This is deprecated as it may have side effects. Component parameters should be treated as DTO, and should not be modified. If you wish to perform some manipulation of the parameter value, then copy it to a local variable, and do your thing.
As pointed out by #enet Blazor component inheritance doesn't behave exactly as one would intuitively expect. This is a cleaner approach when you want to control a UI functionality that can be controlled both internally and externally:
Declare an event in the base component that is raised when the UI state is changed from within the component. Also let the variable that controls the state be a parameter. In you case, something like
PetTemplate.razor:
[Parameter]
public EventCallback OnToggleRequested {get;set;}
[Parameter]
public string Display {get;set;}
protected async Task RaiseToggle()
{
await OnToggleRequested.InvokeAsync();
}
In your PetDog, simple call the toggle method when inside click is raised
PetDog.razor:
<button #onclick="RaiseToggle">Show Details (Inside)</button>
In your container (in this case, index.razor) listen to the event and make changes. Also wire the outside button to the same method:
Index.razor:
<button #onclick="ToggleDisplay">Show Details (Outside)</button>
<PetDog OnToggleRequested="ToggleDisplay" Display="#display"/>
string display = "block";
void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
}
Note that the event can be used at level of hierarchy and you don't need to capture any references anywhere.
I'm using a Razorcomponent with a Blazor server app. The app polls for alertmessages on the server.
The server might send back several messages, which I loop over.
The class on the div has a "show" and "hidden" and that takes care of hiding elements.
The problem I have is that I want to be able to close each alertmessage and not all- which happens as described in the below simplified code:
--snip
#if(alert.valid == true){
#foreach(var alert in alerts){
#if(alert.type == "alert")
<div id="alertmessage" class="#show">
<button type="button" #onclick="#show">Hide this element</button>
</div>
}
}
#code{
private string value { get; set;} = "show";
private void Show() {
value = "hidden";
}
}
As per the above example, if there are several alerts, the method Show() will close all the boxes, and it produces x count of <div id="alertmessage" I get this, but is there a way to grab that specific element like alert.id or something? Appreciate all feedback.
Thanks.
In blazor you work everytime with objects , you should do a class for the alert and change its attribute on the for each.
The page has to contain a list of alert objects as attribute.
More less this:
#if(alert.valid == true){
#foreach(var alert in alerts){
<div id="alertmessage" class="#show">
<button type="button" hidden="#alert.hidden" #onclick="()=>show(alert)">Hide this element</button>
</div>
}
}
#code{
private string value { get; set;} = "show";
private List<Alert> alerts = new();
private void Show(Alert alert) {
alert.hidden = true;
alert.message= "whatever"
}
public class Alert{
public String message = "whatever"
public bool hidden = false;
//other stuff
}
}
If you want to separate the logic from the presentation you can declare alert logic in its own class -file .
I'm new to Blazor and trying to work through some of the basics of how to construct my components and pages. Right now I have a MainLayout that looks like this:
<CascadingValue Value="#layoutVals" Name="LayoutVals">
<Leftbar />
<div class="content-page">
<Topbar />
<div class="content">
<div class="container-fluid">
#Body
</div>
</div>
</div>
</CascadingValue>
#code {
public LayoutValues layoutVals = new LayoutValues()
{
Title = "Dashboard",
Breadcrumbs = new Dictionary<string, string>()
{
{ "Dashboard", "/" }
}
};
}
I'm trying to use the cascading value to allow a child page/component to overwrite values in the Topbar component (i.e. page title, breadcrumb, some other display values that I want consistent across views but dynamically replaced based on the page).
I'm able to access the object in the Topbar component and they are set properly based on what they're initialized to in MainLayout (shown above), and I'm able to override them within that component. However, if I set them in a page the change doesn't seem to make it's way up and then back down the chain to the Topbar component where I want them displayed.
I'm sure I could eliminate the Topbar component and inline everything in my MainLayout but I'd prefer to keep the code clean and separate if it's possible.
The problem you are facing is, that the <Topbar /> is not re-rendered after the value has changed in some component down below the tree (page, etx). You have to tell the Topbar that to render again:
public class LayoutValues
{
public string Title {get;set;}
public Action ValuesChanged;
}
Subscribe to ValuesChanged in Topbar:
protected override void OnInitialized()
{
LayoutVals.ValuesChanged += () => StateHasChanged();
//dont forget to unsubscribe somewhere
}
[CascadingParameter] public LayoutValues LayoutVals {get;set;}
And call it whenever you change the value (or you can do this in setter of LayoutValues):
//some page
private void ButtonClicked()
{
LayoutVals.Title="Changed title";
LayoutVals.ValuesChanged.Invoke();
}
[CascadingParameter] public LayoutValues LayoutVals {get;set;}
Working demo.
This solution has a performance advantage - the app doesn't have to re-render the whole tree, just the Topbar has called the StateHasChanged.
I'm playing around with the custom template in Blazor and I'm trying to find to a way to two-way bind a CascadingValue or achieve something similar. Right now I have the following template.
#if (PopupVisible)
{
<DxPopup>
<HeaderTemplate>
<h4 class="modal-title">#HeaderText</h4>
<button type="button" class="close" #onclick="#UpdatePopupVisible">×</button>
</HeaderTemplate>
<ChildContent>
<div class="modal-body">
<div class="container-fluid">
#bodyContent
</div>
</div>
<div class="modal-footer">
#footerContent
<button class="btn btn-secondary" #onclick="UpdatePopupVisible">Cancel</button>
</div>
</ChildContent>
</DxPopup>
}
#code {
[CascadingParameter] public bool PopupVisible { get; set; }
[CascadingParameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
[Parameter] public RenderFragment HeaderText { get; set; }
[Parameter] public RenderFragment footerContent { get; set; }
[Parameter] public RenderFragment bodyContent { get; set; }
private async Task UpdatePopupVisible()
{
PopupVisible = false;
await PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Then I have a component that implements this template(child), and then I have that component called with a button press(parent). What I want to know is if there is a way to bind the PopupVisible parameter from the parent without having to bind it the child and having the child pass it to the template. I haven't found a way to two-way bind a cascading parameter but if possible I think that would be the best way to do so. Outside of that, I'm not sure if there is another way or I'm going to have to go with my current idea of passing the value.
You can't do two-way binding with cascading parameters. Cascading means flowing downstream, from parent to child, and not the other way around.
I'm not sure I understand your question...however, if you wish to pass a value from a parent component and back; you can do the following:
Note: This is a two-way Component data binding
Child Component
#code
{
private bool visible;
[Parameter]
public bool PopupVisible
{
get { return visible }
set
{
if (visible != value)
{
visible = value;
}
}
}
[Parameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
// Invoke the EventCallback to update the parent component' private field visible with the new value.
private Task UpdatePopupVisible()
{
PopupVisible = false;
return PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Usage
#page "/"
<DxPopup #bind-PopupVisible="visible" />
#code {
private bool visible;
}
Note: If you need some explanation, and believe that I did not answer your question, don't hesitate to tell me, but please take the time to phrase your questions... I could not completely understand questions.
what you can do is, Cascade the parent component and in the child component, access the parent Property you want to change like this:
Parent:
<CascadingValue Value="this">
<Child />
</CascadingValue>
Child:
[CascadingParameter]
public Parent Parent { get; set; }
.....
private void ChangeParentProperty()
{
Parent.Property = ....;
}
Any doubt feel free to ask.
I was watching a tutorial in Blazor. Then I came across this code and I can't seem to find it in the Internet or I think I'm not using the right terms for searching atleast.
#code{
[Parameter]
public IList<Todo> Todo {get; set;}
}
Is it only exclusive in blazor or it is available in c#.
Kindly give some references. Thanks in advance.
This is explained in Create and use ASP.NET Core Razor components, specifically in the Component Parameters section.
[Parameter] is used to mark the component parameters that can be set when the component is used in another page. Borrowing from the doc example this component doesn't have any parameters :
<div class="panel panel-default">
<div class="panel-heading">#Title</div>
<div class="panel-body">#ChildContent</div>
<button class="btn btn-primary" #onclick="OnClick">
Trigger a Parent component method
</button>
</div>
#code {
public string Title { get; set; }
public RenderFragment ChildContent { get; set; }
public EventCallback<MouseEventArgs> OnClick { get; set; }
}
Without the [Parameter] attribute, those are just public properties that can't be set from other pages. The following line would be invalid :
<ChildComponent Title="Panel Title from Parent" />
While this :
<div class="panel panel-default">
<div class="panel-heading">#Title</div>
<div class="panel-body">#ChildContent</div>
<button class="btn btn-primary" #onclick="OnClick">
Trigger a Parent component method
</button>
</div>
#code {
[Parameter]
public string Title { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public EventCallback<MouseEventArgs> OnClick { get; set; }
}
Allows us to set the parameters whenever we use that component :
<ChildComponent Title="Panel Title from Parent"
OnClick="#ShowMessage">
Content of the child component is supplied
by the parent component.
</ChildComponent>
All attributes in C# have to reference a type defining that attribute somewhere. That Blazor code is still C#.
In this case, I believe it it refers to Microsoft.AspNetCore.Components.ParameterAttribute - the documentation is currently MIA, but that may well improve over time. There's more detail in the Blazor documentation.
In general, if you have the code in front of you (generally a good idea when watching a tutorial, if at all possible) you can hover over the attribute in Visual Studio to see its fully qualified name or navigate to it.