【问题标题】:Resetting form and set default value Angular 2 [duplicate]重置表单并设置默认值Angular 2 [重复]
【发布时间】:2017-06-26 13:59:17
【问题描述】:

我正在开发一个简单的 Angular 2 应用程序,但在重置 ngForm 但保持默认值时遇到问题:

预期的行为是单击“重置”时,输入框将重置为其默认值(在本例中为“默认”)以及所有角度特定的类恢复为默认值(即 ng-untouched、ng -原始等)

我看到的是默认值也被清除了,即使我在表单重置后明确设置了它

下面的代码sn-p:

HTML:

<form (ngSubmit)="onTrainSearchClick()" novalidate #trainForm="ngForm">
  <input type="text" [(ngModel)]="id" name="someId"/>
  <button type="button" (click)="reset(trainForm)">Reset</button>
  <button type="submit">Search</button>
</form>

TypeScript(省略了导入和@Component):

export class TrainSearchTestComponent implements OnInit {

  id: string = 'DEFUALT';

  constructor() { }
  ngOnInit() { }
  onTrainSearchClick(){ }

  reset(form: NgForm){
    form.resetForm();
    this.id = 'DEFUALT';
  }
}

【问题讨论】:

    标签: forms angular


    【解决方案1】:

    使用form.reset:

    form.reset({ id: this.id });
    

    原始答案(对 angular@2 有效)

    您可以将值传递给resetForm,该值将用作表单的默认值:

    form.resetForm({ id: this.id });
    

    (当然,如果您的表单是 FormGroup 并且它有一个名为 id 的控件,它应该有一个默认值)

    【讨论】:

    • 这对我有用,但你知道为什么“this.id = 'Default'”行不起作用吗?谢谢
    • 因为您只是将字符串 id 设置为默认值。问题是您没有将您的 id 设置为该值的 FormControl。
    • 我认为方法现在只是重置:form.reset()
    • 像魅力一样工作
    猜你喜欢
    • 2017-06-11
    • 2011-02-09
    • 1970-01-01
    • 2011-04-06
    • 2014-07-11
    • 2018-02-17
    • 2019-01-25
    • 1970-01-01
    • 2021-05-07
    相关资源
    最近更新 更多