0
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray, Validators, FormControl } from '@angular/forms'

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  employeeForm!: FormGroup;
  locations: Array<string>= ['Pune', 'Hyderabad', 'Noida']; 
  skills:  Array<ChoiceClass> = [
    {description: 'descr1', value: 'value1'},
    {description: "descr2", value: 'value2'},
    {description: "descr3", value: 'value3'}
  ];
  mat: MatrixDTO[] = [];
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.initilazieForm();
    this.employeeForm.get('matrix')!.setValue(this.createBaseMatrix())
  }

  
  initilazieForm(): void {
    this.employeeForm = this.fb.group({
      name: 'Name here',
      gender: ['male', [Validators.required]],
      location: '',
      notes: '',
      email: '',
      skills: this.fb.array([], [Validators.required]),    
      matrix: this.fb.array([], [Validators.required]),  
      references: this.fb.array([this.fb.control('')])
    });
  }
  onSubmit(): void {
    console.log(this.employeeForm.value);

  }
  selectLocation(event:any):void{
    this.employeeForm.patchValue({
      location:event.target.value
    });
  }
  addEmail(): void {
    this.references.push(this.fb.control(''));
  }
  removeEmail(index: number): void {
    this.references.removeAt(index);
  }

  get references(): FormArray {
    return this.employeeForm.get('references') as FormArray;
  }

  onCheckboxChange(e:any) {
    const website: FormArray = this.employeeForm.get('skills') as FormArray;
  
    if (e.target.checked) {
      website.push(new FormControl(e.target.value));
    } else {
       const index = website.controls.findIndex(x => x.value === e.target.value);
       website.removeAt(index);
    }
  }

  createBaseMatrix(): MatrixDTO[] {
    this.mat[this.mat.length] = new MatrixDTO();
    this.mat[0].name = "Basic Weight(lbs/3000ft)";
    this.mat[0].customRow=false;
    this.mat[0].items.push({label:'30', customCol:false});
    this.mat[0].items.push({label:'35', customCol:false});
    this.mat[0].items.push({label:'40', customCol:false});
    
    
    this.mat[this.mat.length] = new MatrixDTO();
    this.mat[1] = new MatrixDTO();
    this.mat[1].name = "Basic Weight(g/m2)";
    this.mat[1].customRow=false;
    this.mat[1].items.push({label:'34', customCol:false});
    this.mat[1].items.push({label:'42', customCol:false});
    this.mat[1].items.push({label:'68', customCol:false});
    
    
    console.log(this.mat);
    return this.mat;
  }
  
}


export class MatrixDTO implements cols {
  constructor() {    
    this.name = "";
    this.items = [];   
    this.customRow = false;     
     this.label="";
     this.customCol=false;
  }
  name : string;
  items :Array<cols>;
  customRow:boolean;
  label: string;
  customCol:boolean;
  
}


interface cols {
  label: string;
  customCol:boolean;
}

export class ProductDTO {
  constructor() {
    this.id = "";
    this.name = "";     
  }

  id : string;
  name: string;
}

export class ChoiceClass {
  constructor() {
    this.description = "";
    this.value = "";     
  }

  description : string;
  value: string;
}

and also HTML is as follow for this one :

 <p>employee works!</p>
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
 <label>
     Name : 
     <input type="text" formControlName="name" placeholder="required"/>
 </label>

 <label>
    Location : 
    <select formControlName="location" (change)="selectLocation($event)">
        <option *ngFor="let loc of locations" [value]="loc">
                {{loc}}
        </option>
    </select>
</label>
<label>
  <input type="radio" value="Male" formControlName="gender">
    <span>male</span>
</label>
<label>
  <input type="radio" value="Female" formControlName="gender">
    <span>female</span>
</label>
<h2>Please select what skill you're comfortable working with, if any:</h2>
<label for="website">Website:</label>
<div *ngFor="let skill of skills">
  <label>
    <input type="checkbox" [value]="skill.value" (change)="onCheckboxChange($event)" />
    {{skill.description}}
  </label>
</div>

  <h2>Reference(s)</h2>
  <div formArrayName="references" class="grouping" *ngFor="let ref of references.controls; let i=index">
    <label>
      Reference Email: 
      <input type="text" placeholder="optional" [formControlName]="i">
      <button type="button" id="remove_email"(click)="removeEmail(i)">X</button>
    </label>
  </div>
  <button type="button" (click)="addEmail()">Add Another Reference</button>
    <button id="apply_button">Save</button>
</form>

** How can I pass the matrix array of objects on submit in reactive forms ? and also How I can setup same information when user come on same screen for edit**

Edited One : after applying suggestions from one of answer now I am getting following error :

Console Error

stackblitz

3
  • Can you provide the createBaseMatrix method and how you are setting the controls on HTML? Commented Jun 14, 2021 at 17:15
  • edited with more information Commented Jun 14, 2021 at 17:19
  • two links, in SO: stackoverflow.com/questions/67700663/…, from the great Netanel Basal:netbasal.com/… Commented Jun 14, 2021 at 19:01

1 Answer 1

1

2 Quick things to keep in mind:

  1. If you want the value of a reactive form, form.value will not give you what you want. You may want to use this:
const formValue = this.form.getRawValue();
console.log("Form Value ==>", formValue);
  1. If you want to add things to a form-control, in the method createBaseMatrix(), you are mentioning that the return type of that method is createBaseMatrix(): void {}, which means you are not returning anything. Hence the value is null in your case.

To correct this: Change the return type of that method, and make sure you are returning something and then assign to the formControl by doing this:

createBaseMatrix(): yourReturnType {}

this.form.get('matrix').setValue(this.createBaseMatrix())

// You can use, setValue or patchValue if you are doing it outside the form.
Sign up to request clarification or add additional context in comments.

7 Comments

I tried it but its throwing error in console and still Matrix is null
I made some small edits to that stackblitz. The matrix is not null now. You can see the values there Link: stackblitz.com/edit/…
What in case I make changes from UI to this.mat and i want those changes also need to be updated in form matrix control ?
Thats a whole different issue. Try to create a new question for that. Also, I dont see a formControl with matrix name in the HTML. I am not sure how you are planning on changing this.mat. Generally, you would have to write a valueChanges for matrix formControl and if there are any valueChanges, you will have to either call the same function that you calling to initially update the values or a new function depending on what the need is.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.