【问题标题】:How to set component back to initial state in Angular 2如何在Angular 2中将组件设置回初始状态
【发布时间】:2017-04-18 03:57:37
【问题描述】:

我有一个模态组件,它有一个表单和该表单之外的一些其他变量。组件是这样的:

组件:

export class PersonComponent implements OnInit { 

countPerson: number=0;
persons: Person [] = [];

personForm : FormGroup;

ngOnInit(){
  this.step1Form= this.fb.group({
     firstName: 'Levi',
     lastName:  'Ackerman'
  });
}

submitPerson(person: Person){
  this.persons.push(person);
  this.incrementPerson();
}

incrementPerson(){
  this.count++;
}

}

在模板中:

 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body>
         <label>First Name</label>
         <input type="text" formControlName="firstName">
         <label>LastName Name</label>
         <input type="text" formControlName="lastName">
         <button type="button" (click)="submitPerson()">Submit</button>
      </div>
     <div class="modal-footer">
         <button type="button" data-dismiss="modal">Close</button>
     </div>
   </div> 
</div>

我想将表单控件重置回初始值,并将表单外部的变量设置回初始值。所以基本上我希望整个组件回到初始状态。我希望组件在关闭后重置为初始状态。

【问题讨论】:

  • 您的模态从哪里启动?
  • 模态框由父组件触发。所以modal是一个子组件
  • 您是否尝试在模态窗口中编辑人员数据?
  • 不只是使用表单将人员列表添加到人员数组中。关闭模式后,我希望表单和其他变量恢复到初始状态。因此,persons 数组、count person 和其他变量(我只是不包括它,因为它太多了)等变量回到了初始状态。有没有办法让整个组件恢复到初始状态。
  • 目前正在发生什么。你能创建一个plunker吗?使用来自 answer 的模态作为示例

标签: angular typescript


【解决方案1】:

如果您的 HTML 中有表单(未在提供的 sn-p 中显示),您可以在表单上使用 reset 方法:this.yourFormName.reset()

这会将表单状态重置为原始状态并保持不变。

【讨论】:

  • 重置会重置整个组件还是仅重置表单?我的组件由表单和变量组成。我希望表单以及组件的变量恢复初始值。
  • 这将重置表单。您需要自己更新自己的变量。
  • 在我的代码示例中,我有一个在保存操作后执行的onSaveComplete()。它调用重置方法,然后导航回概览/列表页面。您可以轻松地将其更改为重新初始化所有组件变量。你可以在这里看到我的代码示例:github.com/DeborahK/Angular2-ReactiveForms/tree/master/…
  • 仍然需要知道如何根据问题重置整个组件
猜你喜欢
  • 2017-06-09
  • 1970-01-01
  • 2012-02-16
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多