答案 0 :(得分:1)
切换到反应形式并注册默认状态。
然后可以使用默认状态在表单控件上调用reset
。
<select [formControl]="select">
<option disabled>--Pick an option--</option>
<option *ngFor="let option of options" [value]="option.name" [selected]="selectedOption(option.name)">{{option.name}}</option>
</select>
select: FormControl = new FormControl(this.options[0].name);
defaultState = this.select.value;
constructor() {
this.select.valueChanges.subscribe(value => this.setState(value));
}
...
no() {
this.select.reset(this.defaultState);
this.checkState = false;
}
N.B。 :我使用了表单控件,但同样适用于表单组
答案 1 :(得分:1)
在变量preState
中保留prevois选择的选项,并在用户单击否时将newState
还原为preState
。
export class AppComponent {
state;
newState;
preState;
checkState = false;
options = [
{name:'dormant'},
{name:'active'},
{name:'finished'}
];
setState(state) {
this.preState = this.newState;
this.newState = state
this.checkState = true;
}
selectedOption(option) {
return this.newState === option;
}
yes() {
this.state = this.newState;
this.checkState = false;
}
no() {
this.checkState = false;
this.newState = this.preState;
}
}
更新:
要显示UPDATE中提到的禁用选项,请将[selected]='!newState'
放在禁用选项上:
<select (change)="setState($event.target.value)">
<option disabled [selected]='!newState'>--Pick an option--</option>
<option *ngFor="let option of options" [value]="option.name" [selected]="selectedOption(option.name)">{{option.name}}</option>
</select>
<div *ngIf="checkState" class="check-state">
<p>Are you sure you want to change</p>
<p><span class="bold">{{state}}</span> to <span class="bold">{{newState}}</span></p>
<button (click)="yes()">yes</button><button (click)="no()">no</button>
</div>
答案 2 :(得分:1)
由于您没有使用两种方式绑定,因此您对变量所做的更改不会影响模板。这是我的方法:
HTML文件
<select [(ngModel)]="state" (change)="setState()">
<option disabled [value]="null">--Pick an option--</option>
<option *ngFor="let option of options" [value]="option.name" >{{option.name}}</option>
</select>
<div *ngIf="checkState" class="check-state">
<p>Are you sure you want to change</p>
<p><span class="bold">{{lastState}}</span> to <span class="bold">{{state}}</span></p>
<button (click)="yes()">yes</button><button (click)="no()">no</button>
</div>
TS文件
state;
lastState;
checkState = false;
options = [
{name:'dormant'},
{name:'active'},
{name:'finished'}
];
constructor() {
this.lastState = this.state;
}
setState() {
this.checkState = true;
}
yes() {
this.checkState = false;
this.lastState = this.state;
}
no() {
this.checkState = false;
this.state = this.lastState;
}