Skip to content

Handling User Input

pablocar80 edited this page Feb 15, 2021 · 1 revision

To let users interact with your app, we can use the Event method to attach event listeners that invoke methods on our components:

using Integrative.Lara;

internal class UserInputComponent : WebComponent
{
    int _counter;
    public int Counter { get => _counter; set => SetProperty(ref _counter, value); }

    public UserInputComponent()
    {
        ShadowRoot.Children = new Element[]
        {
            new HtmlDivElement()
                .Bind(this, x => x.InnerText = Counter.ToString()),
            new HtmlButtonElement
                { InnerText = "Increase" }
                .Event("click", () => Counter++)
        };
    }
}

To collect input values from elements, use the method BindBack:

using Integrative.Lara;

internal class UserTextComponent : WebComponent
{
    private string _name;
    public string Name { get => _name; set => SetProperty(ref _name, value); }

    public UserTextComponent()
    {
        Name = "Taylor";
        ShadowRoot.Children = new Element[]
        {
            new HtmlDivElement
                { InnerText = "Please enter your name: " },
            new HtmlInputElement()
                .Bind(this, x => x.Value = Name)  // if property changes, update element
                .BindBack(x => Name = x.Value),   // if element changes, update property
            new HtmlButtonElement
                { InnerText = "Read" }
                .Event("click", () => { }),
            new HtmlDivElement()
                .Bind(this, x => x.InnerText = $"Your name is {Name}"),
        };
    }
}
Clone this wiki locally