2017-04-17 58 views
2

我有一個組件,它是一種具有窗體和其他一些變量的窗體。該組件是這樣的:如何在Angular 2中將組件設置回初始狀態

組件:

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> 

我想重置表單控件返回到初始值和以及設定外的變量的形式回到初始值。所以基本上我希望整個組件回到初始狀態。我希望組件在關閉後重置爲初始狀態。

+0

從哪裏啓動你的模態? – Aravind

+0

模態由父組件觸發。所以模態是一個子組件 – ilovejavaAJ

+0

你是否想要在模態窗口中編輯人員數據? – Aravind

回答

5

如果你的HTML表單(未在所提供的片段所示),您可以在表單上使用復位方法:this.yourFormName.reset()

這將重置表格狀態恢復到原始的和不變的。

+0

將重置重置整個組件或只是形式?我的組件由一個表單和變量組成。我希望表單以及組件的變量回到初始值。 – ilovejavaAJ

+0

這將重置表單。你需要自己更新自己的變量。 – DeborahK

+0

在我的代碼示例中,我有一個保存操作後執行的'onSaveComplete()'。它調用重置方法,然後導航回到總覽/列表頁面。您可以輕鬆地將其更改爲重新初始化所有組件變量。你可以在這裏看到我的代碼示例:https://github.com/DeborahK/Angular2-ReactiveForms/tree/master/APM-Updated – DeborahK

相關問題