【问题标题】:Unable to achieve two way binding in Reactive-form Angular without ngmodel在没有 ngmodel 的情况下,无法在 Reactive-form Angular 中实现两种方式绑定
【发布时间】:2021-07-27 11:38:35
【问题描述】:

以下是我尝试过的,当我在输入字段中添加值后按回车键时,我只看到园艺和绘画,但没有显示我输入的新值。 请帮助我理解我在这里做错了什么..

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);
  }

【问题讨论】:

    标签: angular-reactive-forms reactive-forms two-way-binding


    【解决方案1】:

    因为在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);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 2020-07-07
      • 2019-01-22
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多