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

Initialize Angular reactive form with query parameters

I want to subscribe to route.queryParams and change the default values of a given reactive Form so it will be initialized with that parameters. I am not sure how to initialize them, whether including something in the ngOnInit or maybe in the first argument of the new FormControl (formState) at constructor level:

export class CustomizedTimeDialogComponent implements OnInit {

  dateRangeForm: FormGroup

  constructor(private dialogRef: MatDialogRef<CustomizedTimeDialogComponent>,
              private router: Router,
              private route: ActivatedRoute,
              @Inject(MAT_DIALOG_DATA) public data: any) {
    this.dateRangeForm = new FormGroup({
      'startDate': new FormControl(----->¿?¿?¿?¿?¿?¿?<-----, [Validators.required]),
      'endDate': new FormControl(----->¿?¿?¿?¿?¿?¿?<-----, [Validators.required])
    });

  }

  ngOnInit(): void {
    this.route.queryParams
      .subscribe(params => {
        ----->¿?¿?¿?¿?¿?¿?<-----
      })
  }

  [...]

}

>Solution :

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

First of all, you need to initialise the dateRangeForm in onInit and inside subscribe patch the form like this-

this.route.queryParams
  .subscribe(params => {
    this.dateRangeForm.patchValue({
       'startDate': params.startDate, 
       'endDate': params.endDate
    }) 
})
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