How to reset Control value

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

I'm trying to make a control where we can enter multiple player with tag and their score.

But when we click on my AddPlayer Button I create a player then I need to reset the form control value to default.

I've tried a lot of things but nothing works .... it never changes the view value.

Here is the code:

addPlayer(form: ControlGroup) {     var player = new Player();     player.tag = form.value.tag;     player.name = form.value.name;     player.score = form.value.score;      // nothing work     form.value = null;     form.value.tag = null;     form.value.tag = '';      this.playerService.addPlayer(player.tag, player.name, player.score);     this.newplayer.next(player); } 

Here is the html

<form (submit)="addPlayer(playerForm)" [ng-form-model]="playerForm">     <div class="form-group" [class.has-error]="!playerForm.find('tag').valid && playerForm.find('tag').touched">         <div class="col-md-3 text-right">             <label for="tag">Tag: </label>         </div>          <input type="text" id="tag" #tag="form" [ng-form-control]="playerForm.controls['tag']"  placeholder="Tag"/>          <span *ng-if="tag.control.hasError('required') && !tag.control.pristine">Tag is required</span>     </div>      <div class="form-group" [class.has-error]="!playerForm.find('name').valid && playerForm.find('name').touched">         <div class="col-md-3 text-right">             <label for="name">Player Name: </label>         </div>          <input type="text" id="name" #name="form" [ng-form-control]="playerForm.controls['name']" placeholder="Player Name" />          <span *ng-if="name.control.hasError('required') && !name.control.pristine">Player Name is required</span>     </div>      <div class="form-group" [class.has-error]="!playerForm.find('score').valid && playerForm.find('score').touched">         <div class="col-md-3 text-right">             <label for="score">Score: </label>         </div>          <input type="number" id="score" #score="form" [ng-form-control]="playerForm.controls['score']" value="0" min="0" max="200" />          <span *ng-if="score.control.hasError('required') && !score.control.pristine">Score is required</span>     </div>      <button type="submit" class="btn btn-primary">         Add Player     </button> </form> 

So how can i reset the value of the control?

回答1:

To reset the form the easiest way is rebuild the form builder. After clicking the add player button

this.playerForm = this.builder.group({         'name': [...],         'tag': [...],         'score': [...]     }); 


回答2:

for(let c in form.controls) {     form.controls[c].updateValue(''); }; 


回答3:

According to angular 2 docs it looks like the updateValue has some params like only self and emitEvent which seem to handle the validation reset. Have you tried that?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!