如何将 angular 控件的值重置回其绑定?

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

我有一个绑定到数据的控件。

<input [value]="myData">

这是一种绑定方式。可以说我在输入中输入了一些东西。 myData不会变。如何将控件值重置回 myData

这是一种用代码实现的方法:

  1. myData 设置为不同的值(例如空字符串)
  2. 致电ChangeDetectorRef.detectChanges
  3. myData 设置回原来的值
public myData = "Hello world!";

constructor(private changeDetectorRef: ChangeDetectorRef) { }

private refreshInputDisplay(): void {
    const oldData = this.myData;
    this.myData = "";
    this.changeDetectorRef.detectChanges();
    this.myData = oldData;
}

有关演示,请参阅 this stackblitz

您可以使用 ViewChild 并相应地设置其值:

HTML

<input [value]="myData" #oneWayInput />

组件 TS

// A property in your component
@ViewChild('oneWayInput') oneWayInput: ElementRef;

// When you want to revert the value in the input
this.oneWayInput.nativeElement.value = this.myData;

或者您可以使用双向绑定,在单独的变量中捕获初始值,然后在需要时随时将绑定值设置为初始值:

initialValue: string;
myData: string;

// Where you set myData
this.initialValue = this.myData;

// Reset value
this.myData = this.initialValue;