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

Time:08-26

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.

Live Demo

CodePudding user response:

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();
});
  • Related