'InputText component behaves unexpectedly

To add events and formatters to the InputText component of Blazor, I have created an inherited component, InputText2.

It looks like this:

public class InputText2 : InputText
{
    [Parameter]
    public Action<string> OnBlur { get; set; }

    [Parameter]
    public Func<string, string> Formatter { get; set; }

    protected override bool TryParseValueFromString(string value, out string result, [NotNullWhen(false)] out string validationErrorMessage)
    {
        var parseResult = base.TryParseValueFromString(value, out result, out validationErrorMessage);

        OnBlur?.Invoke(value);

        return parseResult;
    }

    protected override string FormatValueAsString(string value)
    {
        var result = Formatter?.Invoke(value) ?? value;
        //CurrentValueAsString = result;

        return result;
    }
}

The Formatter parameter takes a Func that modifies the string in some way. In my example, I wanted postal codes in the format "12345" to be formatted "123 45". In FormatValueAsString, result gets the correct value, but this is not reflected in the UI after rendering. However, if I do set CurrentValueAsString to result, then it works. But I can't find any reason for this. And in other examples, that property is never touched either. Also, it seems to be able to create loops between FormatValueAsString and TryParseValueFromString.

Anyone seen this before?



Solution 1:[1]

FormatValueAsString is just used by InputBase to format the CurrentValue in the getter for CurrentValueAsString.

The value that is bound to the input control and hence what you see on the page is the value of CurrentValue

So, if you want the displayed value to use the formatted value, you need to set CurrentValue to that formatted value - and this is what happens when you include the line to set CurrentValueAsString = result - the setter on CurrentValueAsString sets CurrentValue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mister Magoo