以下是我尝试过的,当我在输入字段中添加值后按回车键时,我只看到园艺和绘画,但没有显示我输入的新值。 请帮助我理解我在这里做错了什么..
template file:
<div formArrayName="hobbies">
<h4>Your Hobbies</h4>
<input type="text" class="form-group" (keyup.enter)="onAddHobby()">
<ul class="list-group">
<li *ngFor="let hobby of signUpForm.get('hobbies')['controls'];let i=index"
class="list-group-item">{{hobby.value}}</li>
</ul>
</div>
typescript file:
ngOnIt{
'hobbies': new FormArray([new FormControl('Gardening'), new FormControl('Painting')])
}
onAddHobby(){
const control= new FormControl('', Validators.required);
(<FormArray>this.signUpForm.get('hobbies')).push(control);
}
答案 0 :(得分:0)
因为在 onAddHobby()
方法中,每次按下回车键时,您都会推入空的表单控件。从事件接收值并将其传递给 formControl 看起来像,
在 HTML 中,
(keyup.enter)="onAddHobby($event.target.value)"
在 Ts 中,
onAddHobby(value){
const control= new FormControl(value, Validators.required);
(<FormArray>this.signUpForm.get('hobbies')).push(control);
}