forms input are not set in ng bootstrap modal

57 views Asked by At

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

2

There are 2 answers

0
Seema Sharafat On BEST ANSWER

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.

1
Mohamed Shaik Mahsook M A On

Alright, let's troubleshoot this together!

Firstly, let's make sure the data is actually making its way into the modal. In your modal component, add some logging to check if the question is arriving as expected.

constructor(public modal: NgbActiveModal, private formBuilder: FormBuilder) {
  console.log("Question in the modal:", this.question);

  // ... rest of your code
}

If you see the question printed correctly, then the issue might be elsewhere. If not, double-check how you're passing the data when opening the modal:

modalRef.componentInstance.question = item.question;

Ensure item.question has a valid value at this point.

Next, let's check the template. Make sure you're binding to the correct form controls in your HTML:

<input formControlName="question" id="questions" class="form-control" name="questions" />

Check for any typos in the form control names.

If everything seems correct so far, let's add a quick check to see if the form is initialized with the correct values. Update your modal component like this:

ngOnInit(): void {
  console.log("Form initialization - question:", this.question);

  // ... rest of your code
}

Check if this log shows the correct value for the question when the modal is initialized.

If you still can't figure it out, let me know the results of these checks, and we can dive deeper!