Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular on EventEmitter @input data clear getting error in schema form

when the form submitted, getting error from form as Error: Cannot read properties of undefined (reading 'name')

import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
  VERSION,
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';

import { FormSchema } from '../form.schema';

@Component({
  selector: 'shared-form',
  templateUrl: './shared.form.html',
})
export class SharedForm implements OnInit, OnDestroy {
  @Input() schema = FormSchema;
  @Output() userFormOnSubmit = new EventEmitter();
  userForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: new FormControl('', [Validators.required]),
      username: new FormControl('', [Validators.required]),
    });
  }
  ngOnInit() {
    // this.schema.forEach((item) => {
    //   if (item.formControl === item.controlName) {
    //     this.userForm.get(item.controlName).setValue(item.value);
    //   }
    // });
  }
  updateForm($event) {
    $event.preventDefault();
    this.userFormOnSubmit.emit(this.userForm.value);
  }
  ngOnDestroy() {
    console.log('callss');
  }
}

template:

<div>
  {{schema|json}}
  <form [formGroup]="userForm" (submit)="updateForm($event)">
    <div *ngFor="let element of schema">
      <label>{{ element.name }}</label>
      <input [type]="'element.type'" [formControlName]="element.formControl" />
    </div>
    <button type="submit">Submit</button>
  </form>
</div>

How to fix this? do not know why the @input() value cleared. any correct way to update the value to parent.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Live Demo

>Solution :

You have an error in using the map method — you need to return a value:

this.newFormSchema = this.newFormSchema.map((item) => {
  item.value = update[item.name] + new Date();
  return item; // !
});

Also, here you can use forEach:

this.newFormSchema.forEach((item) => {
  item.value = update[item.name] + new Date();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading