[英]Unable to setValue into reactive forms for second time after resetting the form
Using reactive forms, when we click on edit a particular user using setValue methods am populating into form controls.使用响应式表单,当我们单击编辑特定用户时,使用 setValue 方法填充到表单控件中。 Then when i click on save button i am clearing the form using reset() method.
然后,当我单击保存按钮时,我正在使用 reset() 方法清除表单。
Now if click on the edit button for another user i am populating the data same as above, but setValue or patchValue is not adding data into form fields现在,如果单击另一个用户的编辑按钮,我将填充与上面相同的数据,但 setValue 或 patchValue 不会将数据添加到表单字段中
https://stackblitz.com/edit/angular-dzyjig https://stackblitz.com/edit/angular-dzyjig
Your problem is related to Change Detection .
您的问题与Change Detection相关。
Problem with your code:您的代码有问题:
You are sending the value from parent component to child component and you are calling your edit
method inside the ngOnChanges
which will run during Angular Change Detection.您正在将值从父组件发送到子组件,并且您正在
ngOnChanges
中调用您的edit
方法,该方法将在 Angular 更改检测期间运行。
In your parent component edit
method, you have:在您的父组件
edit
方法中,您有:
edit(user){
this.user = user;
console.log(this.user);
}
Now if you click on the same user edit button, this.user
will not change and it will not trigger the ngOnChanges
method of your child component and your form will not populate.现在,如果您单击同一个用户编辑按钮,
this.user
不会更改,也不会触发子组件的ngOnChanges
方法,并且不会填充您的表单。
Solution:(You can find the working stackbliz demo here )解决方案:(您可以在此处找到工作的 stackbliz 演示)
You need to change the value of the user every time even when you click on the same user edit button and trigger change detection manually.即使您单击同一个用户编辑按钮并手动触发更改检测,您也需要每次更改用户的值。
import { Component } from '@angular/core';
import { FormGroup, Validators, FormBuilder} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(private formBuilder: FormBuilder, private cd: ChangeDetectorRef){
}
edit(user){
this.user = null;
this.cd.detectChanges();
this.user = user;
console.log(this.user);
}
}
Your ngOnChanges
will look like this:您的
ngOnChanges
将如下所示:
ngOnChanges(){
if(this.user) {
this.edit();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.