angularng-bootstrap-modal

forms input are not set in ng bootstrap modal


im trying to create a modal that has formgroup ,im calling the modal from from another component and im passing the parameter by using this code

modalRef.componentInstance.question=item.question
etc....

till now everything is fine im able to read that variable from the modal but my problem is the formcontrol is always empty here is my code for the modal

import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-modalinput2',
  templateUrl: './modalinput2.component.html',
  styleUrls: ['./modalinput2.component.css']
})
export class Modalinput2Component implements OnInit {
  @Input() question: string = "";
  @Input() answer: string = "";
  @Input() department: string = "";
  @Input() category: string = "";
  @Input() id: string = "";

  myForm: FormGroup;

  constructor(public modal: NgbActiveModal, private formBuilder: FormBuilder) {
    console.log("printing from mdoal "+this.question)
    this.myForm = this.formBuilder.group({
      question: ['', [Validators.required, Validators.minLength(3),Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)]],
      answer: ['', [Validators.required, Validators.minLength(3), Validators.pattern(/[\S]/g)]],
      department: [''],
      category: [''],
    });
  }
  ngOnInit(): void {

  }

  getErrorMessage(control: AbstractControl | null): string {
    if (control?.errors) {
      const errorKey = Object.keys(control.errors)[0];
      const errorMessages: Record<string, string> = {
        required: 'This field is required.',
        minlength: 'Minimum length is ' + control.errors?.['minlength']?.requiredLength + ' characters.',
        maxlength: 'the max length is '+control.errors?.['maxlength']?.requiredLength + ' characters.'
       
      };

      return errorMessages[errorKey] || 'Invalid input.';
    }
    return '';
  }

  write() {
    if (this.myForm.valid) {
      const formData = {
        "question": this.myForm.value.question,
        "answer": this.myForm.value.answer,
        "department": this.myForm.value.department,
        "category": this.myForm.value.category,
        "id": this.id
      };

      
      this.modal.close(formData);
    } else {
      console.log("Form is invalid. Please check the input values.");
    }
  }
  
}

and here the html for it

<div class="modal-header modal-lg">
    <h4 class="modal-title" id="modal-basic-title">Profile update</h4>
    <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
  </div>
  
  
  
  <div class="modal-body">
    <form [formGroup]="myForm">
      <div class="mb-3">
        
        <label for="questions">Question</label>
        <div class="input-group3">
          <input formControlName="question" id="questions" class="form-control" name="questions" />
        </div>
        
        <div *ngIf="myForm.get('question')?.invalid && myForm.get('question')?.touched" class="text-danger">
          {{ getErrorMessage(myForm.get('question')) }}
        </div>
  
      
        <label for="answer">Answer</label>
        <div class="input-group2">
          <input formControlName="answer" id="answer" class="form-control" name="answer" />
        </div>
        
        <div *ngIf="myForm.get('answer')?.invalid && myForm.get('answer')?.touched" class="text-danger">
          {{ getErrorMessage(myForm.get('answer')) }}
        </div>
  
        
        <label for="department">Department</label>
        <div class="input-group">
          <input formControlName="department" id="department" class="form-control" name="department" />
        </div>
  
        
        <label for="category">Category</label>
        <div class="input-group">
          <input formControlName="category" id="category" class="form-control" name="category" />
        </div>
      </div>
  
    </form>
  </div>
  
  
  
  
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="write()">Save</button>
  </div>

i remember this was working but i messed with something and now it's not working


Solution

  • It seems there is issue in form initialization while doing in constructor, Trying to moving this.myForm = this.formBuilder.group..... code snippets from constructor to ngOnInit() and then check.