Raza Ellahi
Raza Ellahi

Reputation: 63

The value property in reactive forms does not initializes the form control name

I am using reactive forms in which I want two way data binding, therefore i used "value" property to initialize the default values of form group. because form group is in ngFor loop but when I tried to get the form I only get edited values and can't get the default i seems that "value" property does not initializes the form control, It only display in the DOM.

TS:

 userForm: FormGroup;

 constructor(private fb: FormBuilder){}

 ngOnInit(){
    this.userForm = this.fb.group({
  userName: [''],
  fullName: [''],
  email: [''],
 });
   }

OnUpdateClick() {

 console.log(this.userForm.get('userName').value);
 console.log(this.userForm.get('fullName').value);
 console.log(this.userForm.get('email').value);

 }

HTML:

   <div *ngFor="let agent of agents">

    <form [formGroup]="userForm" >

                    <mat-form-field >
                      <mat-label>Name</mat-label>
                      <input matInput id="Name" name="name" value=" 
                     {{agent.username}}" formControlName="userName">
                    </mat-form-field>

                    <mat-form-field >
                      <mat-label>Name</mat-label>
                     <input matInput id="FName" name="Fname" value=" 
                     {{agent.fullName}}" formControlName="fullName">
                    </mat-form-field>

                      <mat-form-field >
                      <mat-label>Name</mat-label>
                     <input matInput id="email" name="email" value=" 
                     {{agent.email}}" formControlName="email">
                    </mat-form-field>

              <button (click)="OnUpdateClick()"> SAVE </button>

   </div>

When i try to get the form fields in "OnUpdateClick" function, I only get those values which i made dirty, the untouched controls should also returns their default values

Upvotes: 0

Views: 5228

Answers (2)

Eliseo
Eliseo

Reputation: 58039

Raza, At first, say that, using ReactiveForm, really we are not binding data, we create a form so in form.value we have the data. You can see write in your .html -just for check-

{{userForm?.value|json}}

I like create a function like

constructor(private fb: FormBuilder){}

createForm(data:any):FormGroup
{
   return this.fb.group({
      userName: [data?data.userName:null],
      fullName: [data?data.fullName:null],
      email: [data?data.email:null],
   });
}

If you has a unique agent you can do, when has an agent

ngOnInit(){
    this.userForm = this.createForm(agent);
}

If your agents are from a call to a service

ngOnInit(){
    this.mayService.getAgent().subscribe(data=>
    {
        this.userForm = this.createForm(data);
    })
}

Well, you has an array of Agents, and I don't know what do you want to get in userForm .value. If you want to get and array of object, take account Dhara's response and my comment

myArrayForm:ArrayForm; //declare an array Form
ngOnInit(){
    this.myArrayForm= this.fb.array(agents.map(a=>this.createForm(a));
    //Its a abreviate way to say
    //this.myArrayForm=[];
    //for (let i = 0; i < this.agents.length; i++) {
    //     this.userDataArray.push(agents[i]);
    //}       
}

And the .html

<form [formGroup]="myArrayForm" (submit)="save(myArrayForm)" >
      <div *ngFor=" let agent of myArrayForm.controls;let i = index"
           [formGroupName]="i">
         <mat-form-field >
             <mat-label>User Name</mat-label>
             <input matInput id="Name" name="name"  formControlName="userName">
         </mat-form-field>
         <mat-form-field >
              <mat-label>Full Name</mat-label>
              <input matInput id="FName" name="Fname"  formControlName="fullName">
         </mat-form-field>
         <mat-form-field >
              <mat-label>E-mail</mat-label>
              <input matInput id="email" name="email" formControlName="email">
         </mat-form-field>
      </div>
    </div>
    <button> SAVE </button>
</form>

save(myForm)
{
   console.log(myForm.value)
}

But you can want to have an array of FormGroup

myArray:FormGroup[] //declare an array of FormGroup
ngOnInit(){
    this.myArray= agents.map(a=>this.createForm(a));
    //Its a abreviate way to say
    //this.myArray=[];
    //for (let i = 0; i < this.agents.length; i++) {
    //     this.myArray.push(this.createForm(agents[i]));
    //}       
}

And the .html

<form *ngFor="let form of myArray" [formGroup]="form">
     <mat-form-field >
         <mat-label>User Name</mat-label>
         <input matInput id="Name" name="name"  formControlName="userName">
     </mat-form-field>
     <mat-form-field >
          <mat-label>Full Name</mat-label>
          <input matInput id="FName" name="Fname"  formControlName="fullName">
     </mat-form-field>
     <mat-form-field >
          <mat-label>E-mail</mat-label>
          <input matInput id="email" name="email" formControlName="email">
     </mat-form-field>
</form>
<button (click)"save()"> SAVE </button>

save()
{
    myArray.forEach(form=>{
        console.log(form.value)
    }
}

Upvotes: 1

Dharan
Dharan

Reputation: 262

you need to create formarray and patch the formcontrolname values.

       userForm: FormGroup;

          constructor(private fb: FormBuilder){}
       ngOnInit(){
          this.userForm = this.fb.group({
              userData: this.fb.array([]) 
           });
          this.addUserData();
       }
       get userDataArray() {
           return this.userForm.get('userData') as FormArray;
        }
       addUserData() {
         for (let i = 0; i < this.agents.length; i++) {
            const datas =  this.fb.group({
                 userName: [this.agents[i].userName],
                  fullName: [this.agents[i].fullName],
                  email: [this.agents[i].email],
                 });
      this.userDataArray.push(datas);
        }         
            }
OnUpdateClick() {

 console.log(this.userForm.value);

 }

change your html like below; ngfor for reacctive form array and add formarray name.don't need to bind values.

    <form [formGroup]="userForm" >
 <div formArrayName="userData">
      <div *ngFor=" let agent of userDataArray.controls;let i = index" [formGroupName]="i">
                        <mat-form-field >
                          <mat-label>Name</mat-label>
                          <input matInput id="Name" name="name"  formControlName="userName">
                        </mat-form-field>

                        <mat-form-field >
                          <mat-label>Name</mat-label>
                         <input matInput id="FName" name="Fname"  formControlName="fullName">
                        </mat-form-field>

                          <mat-form-field >
                          <mat-label>Name</mat-label>
                         <input matInput id="email" name="email"  formControlName="email">
                        </mat-form-field>



                       </div>
            </div>
          <button (click)="OnUpdateClick()"> SAVE </button>
             </form>

Upvotes: 0

Related Questions