Skip to content

Clarify: Don't create components that write to their own component parameters, use a private field instead.  #18144

@siloimwald

Description

@siloimwald

Don't create components that write to their own parameter properties

While i do understand the general issue and the example given, it is somewhat left unclear how custom form components should deal with that? Does that only apply to hardcoded/literal values?
Does "don't write" mean don't change the reference but altering the object the reference points to is fine? Or should you always use a private backing field for a Parameter-Property a child component is altering?

My understanding was, once i bind (so @bind-varName= .. not just varName = ... ) a value to a parameter of my component, i do expect it to write to that variable. Maybe that's left out because people assume that to be clear?

As a concrete example, i wrote a multi-select component to be used within forms. The parent component (that is, the whole form) binds to a list of the current choices (just int primary keys from a database).
Parent does:
<MultiKeySelect ItemPool="AvailableLabels" @bind-SelectedIDs="Model.ProjectLabelsId" MakeAChoiceText="@L["Projects_Label_SelectALabel"]" />
where SelectedIDs is a int-List within some view model.

Child (MultiKeySelect) has the following Parameter declaration

[Parameter]
public List<int> SelectedIDs { get; set; } 

[Parameter]
public EventCallback<List<int>> SelectedIDsChanged { get; set; }

The child component upon user interaction then proceeds to call Add/Remove directly on the SelectedIDs property and invokes the Changed callback. Which works fine. Does it only work because i did not yet trigger any of the two conditions where the parameter is overwritten? Or is this the way it's supposed to be done?
My assumption would be that through the binding, both parent and child work with the exact same object, so even if it is reset through a re-render it should preserve the current state?
Also, for this particular example, assume the reference the parent provided is null (e.g. there is no selection yet), is the child allowed to "new-up" a collection and would that correctly propagate to the parent?

The password example in the docs section about data-binding does write to its parameter, which is exactly what you shouldn't do?
So either i'm missing something obvious or this particular part of the documentation is slightly unclear or confusing.

Sorry in advance if opening an issue isn't the proper way to address this kind of thing :)


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

Done

Relationships

None yet

Development

No branches or pull requests

Issue actions