angular - 如何在 Angular 2 中将组件设置回初始状态

标签 angular typescript

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

组件:

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>

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

最佳答案

如果您的 HTML 上有一个表单(未在提供的代码段中显示),您可以在表单上使用重置方法:this.yourFormName.reset()

这会将表单状态重置为原始且未更改。

关于angular - 如何在 Angular 2 中将组件设置回初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458084/

相关文章:

typescript - "Inject"带有异步/等待的回调

angular - 模块 'StateService' 声明的意外值 'DynamicTestModule'

c# - Angular 应用程序适用于 http ://localhost:4200, 但我想要 https://localhost:44325

javascript - 隐藏输入不会触发 React 的 onChange 事件

typescript - 如何配置 VSCode 以运行 Yarn 2(使用 PnP)驱动的 TypeScript

html - Angular 2 全局键检测

javascript - 如何在 html 中单击时绑定(bind) NgbModalOptions 大小

Angular 2 拖放

angular - 如何在 Angular 服务中正确检索和缓存数据

Angular 2 : Global AppInjector. 如何避免警告 "circular dependency"