GrahamJRoy
GrahamJRoy

Reputation: 1643

Angular 10 Component Input Into Reactive Form Default Values

I have a component that takes various inputs which are in turn used in a select within a reactive form within that component. The form should use the values as default values in the form but it always seems that they have not been initialised when I try and create the form.

export class GenericFilterComponent implements OnInit {

  @Input() stageOptions: IKeyValuePair[];
  ...

  myForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    console.log(this.stageOptions);
    this.myForm = this.fb.group({
      stages: [this.stageOptions.map(item => item.key), Validators.required],
      ...

this should populate the stages property on the form with an array of key values from the statusOptions input. The console log however shows the array to be empty

[]

When I read through the angular lifecycle hooks docs https://angular.io/guide/lifecycle-hooks it says that ngOnInit is called after ngOnChanges which:

Called before ngOnInit() and whenever one or more data-bound input properties change.

So I would have thought the input values would have been set. I have tried with the other lifecycle hooks, putting them out to the console, and it is only the: ngOnchanges(), ngDoCheck(), ngAfterContentChecked() and ngAfterViewChecked() that log the array, eventually. But these are called many times.

The html

<mat-form-field appearance="fill">
  <mat-label>Stage</mat-label>
  <mat-select formControlName="stages" multiple required>
    <mat-option [value]="-1" (click)="selectAllStages(stage)" #stage>Select All</mat-option>
    <mat-option *ngFor="let stage of stageOptions" [value]="stage.key">{{stage.value}}
    </mat-option>
  </mat-select>
</mat-form-field>

How should I be trying to set default values in my reactive form in the component lifecycle?

Upvotes: 4

Views: 554

Answers (1)

Fahad Subzwari
Fahad Subzwari

Reputation: 2335

Just do like this in your component.ts

myForm: FormGroup;

create_form() {
  this.myForm= new FormGroup({
    stages: new FormControl(['one','two', 'three'], [Validators.required]),
    ...
  });
}

and call this function in your constructor

  constructor() {
    this.create_form();
  }

Upvotes: 0

Related Questions