-1

I have a form and researching here discovered a way to check whether the form is valid or not and to put your data in the URL when submitted. However, if you open another page with the parameters in the URL, the form is not filled in automatically. I would like to know how I can fill it in immediately after the page is loaded. I'm not sure if I have to handle this in the routes or in the typescript.

also the problem of objects being sent in their entirety in the URL

note: Angular/primeng 19

ValidForm() {
    if (this.form.valid) {
      console.log('form valid')
      const queryParams = { ...this.form.value };
      console.log(queryParams)
      this.router.navigate([''], {
        queryParams: queryParams,
        queryParamsHandling: 'merge',
      });
    } else {
      console.log('Form invalid!');

    }
  }

Below is the repository link with the code: https://github.com/ViniciusDevelopment/modelo19

enter image description here

2
  • What have you tried so far? Can you include a minimal, reproducible example or include the problem code? I'd like to help, but I don't have the time to look through your entire repo. Commented Jan 17 at 19:08
  • I researched a lot but I didn't find any documentation on how to do this in the last 3 versions of Angular, only in very old versions that are no longer available. Commented Jan 17 at 19:15

1 Answer 1

0

You can use Angular ActivatedRoute along with ngOnInit life cycle hook for you benifit in your case. In your component inject the activated route to your constructor and in the ngOnInit life cycle check if the the route incoming has parameters if so set the values to the form, else keep it fresh form. on clicking submit ValidForm sumbmitting parse respective data through the URL parameters or pass the data to the API.

Refer the code below for reference:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
  form: FormGroup;

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute, // Inject AcitvatedRoute here
    private router: Router
  ) {

    this.form = this.fb.group({ // Initialize the form
      details: [''], // Field that could store serialized object data
    });
  }

  ngOnInit(): void {
    this.route.queryParams.subscribe((params) => { // Read query parameters
      for (const key in params) {
        if (this.form.contains(key)) {
          try { 
            this.form.get(key)?.setValue(JSON.parse(params[key]));
          } catch {
            this.form.get(key)?.setValue(params[key]); // Set the value to form
          }
        }
      }
    });
  }

  ValidForm(): void {
    if (this.form.valid) {
      console.log('Form is valid');
      const queryParams: any = { ...this.form.value }; // Get query params

      for (const key in queryParams) {
        if (typeof queryParams[key] === 'object') {
          queryParams[key] = JSON.stringify(queryParams[key]);
        }
      }
      
      this.router.navigate([''], { // Navigate and update the URL with form data
        queryParams: queryParams,
        queryParamsHandling: 'merge', // Keeps existing query params
      });
    } else {
      console.log('Form is invalid');
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.