我正在尝试制作一个控件,我们可以输入带有标签和分数的多个玩家。
但是当我们点击我的AddPlayer按钮时,我创建了一个播放器,然后我需要将表单控件值重置为默认值。
我尝试了很多东西,但没有任何作用......它永远不会改变视图值。
以下是代码:
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);
}
这是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>
那么如何重置控件的值?
答案 0 :(得分:2)
要重置表单,最简单的方法是重建表单生成器。 单击添加播放器按钮
this.playerForm = this.builder.group({
'name': [...],
'tag': [...],
'score': [...]
});
答案 1 :(得分:0)
for(let c in form.controls) {
form.controls[c].updateValue('');
};
答案 2 :(得分:-1)
根据angular 2 docs,看起来updateValue有一些params,比如self和emitEvent似乎处理验证重置。你试过了吗?