Angular中禁用Input后重新启用如何保留原有输入值?
解决方案
步骤1:添加输入值绑定与保存变量
给输入框加上双向数据绑定,同时在组件类里新增变量存储禁用前的输入值:
模板代码修改:
<form class="example-form"> <mat-form-field class="example-full-width"> <mat-label></mat-label> <!-- 添加双向绑定关联输入值 --> <input matInput placeholder="Ex. Pizza" [disabled]="filterValue" [(ngModel)]="inputValue" /> <mat-label *ngIf="filterValue">Search</mat-label> <mat-label *ngIf="!filterValue"> No Search</mat-label> </mat-form-field> <button mat-raised-button (click)="filter()">Basic</button> </form>
组件类代码修改:
filterValue: boolean = false; // 绑定输入框当前值 inputValue: string = ''; // 存储禁用前的输入值 savedInputValue: string = ''; filter() { this.filterValue = !this.filterValue; if (this.filterValue) { // 禁用时保存当前输入值,再清空输入框 this.savedInputValue = this.inputValue; this.inputValue = ''; } else { // 启用时恢复之前保存的值 this.inputValue = this.savedInputValue; } }
步骤2:引入FormsModule
因为用到了ngModel双向绑定,需要在对应模块(比如AppModule)中导入FormsModule,否则绑定会失效:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // 其他导入项 FormsModule ] }) export class AppModule { }
修改完成后,点击按钮禁用输入框时,会自动保存当前输入内容并清空输入框;再次点击启用时,之前输入的内容会自动恢复到输入框中。
内容的提问来源于stack exchange,提问作者KrzysztofBojarczuk
相关产品推荐
相关产品推荐

