Home > Mobile >  Initialize Angular reactive form with query parameters
Initialize Angular reactive form with query parameters

Time:10-25

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 => {
        ----->¿?¿?¿?¿?¿?¿?<-----
      })
  }

  [...]

}

CodePudding user response:

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