Search code examples
angularangular-forms

How do I reset an angular control's value back to its binding?


I have a control that is binded to data.

<input [value]="myData">

This is one way binding. Lets say I type something in the input. myData will not change. How do I reset the control value back to myData?


Solution

  • Here is one way to do it in code:

    1. Set myData to a different value (e.g. an empty string)
    2. Call ChangeDetectorRef.detectChanges
    3. Set myData back to it original value
    public myData = "Hello world!";
    
    constructor(private changeDetectorRef: ChangeDetectorRef) { }
    
    private refreshInputDisplay(): void {
        const oldData = this.myData;
        this.myData = "";
        this.changeDetectorRef.detectChanges();
        this.myData = oldData;
    }
    

    See this stackblitz for a demo.