typescript 如何在 Angular 2 中将组件设置回初始状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43458084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set component back to initial state in Angular 2
提问by ilovejavaAJ
I have a component that is a modal which has a form and some other variables outside of that form. The component is something like this:
我有一个模态组件,它有一个表单和该表单之外的一些其他变量。该组件是这样的:
The component:
组件:
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++;
}
}
In the template:
在模板中:
<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>
I want to reset the form controls back to initial values and as well set the variables outside of the form back to initial value. So basically I want the whole component be back to initial state. I want the component be reset to initial state once closed.
我想将表单控件重置回初始值,并将表单外部的变量设置回初始值。所以基本上我希望整个组件回到初始状态。我希望组件在关闭后重置为初始状态。
回答by DeborahK
If there is a form on your HTML (not shown in the provided snippet) you can use the reset method on the form: this.yourFormName.reset()
如果您的 HTML 中有一个表单(未显示在提供的代码段中),您可以在表单上使用 reset 方法: this.yourFormName.reset()
This resets the form state back to pristine and unchanged.
这会将表单状态重置为原始状态且未更改。