Search code examples
htmlarraysangulartypescriptform-control

Set value to Array inside FormControl


I have an FormControl that's declared as an Array of a specific type and I need to populate it with another array of the same type but, I can't figure out how to do so. Here's my code:

profileData = new FormGroup({
  // Some Form Controls here...
  selectedInterests: new FormControl([], Validators.required)
});

constructor(
  public cookieService: CookieService,
  public router: Router,
  private profileService: ProfileService,
  private snackBar: MatSnackBar,
  private translateService: TranslateService
) {
  this.loadUserProfile();
}

private loadUserProfile() {
  this.profileService.loadProfile(this.cookieService.get('UserId')).then(loadedProfile => {
    this.profile = loadedProfile;
    // Data loads here...
    this.profileData.controls['selectedInterests'].setValue(loadedProfile.interests);
    // This line gives the error:
    //   Argument of type 'Interest[]' is not assignable to parameter of type 
    //   'never[]'.
    //   Type 'Interest' is not assignable to type 'never'.
    this.cookieService.get('UserId');
  });
}

I selected only the parts that are important for the question, I can add more info if needed.

HTML:

          <mat-form-field>
            <mat-label>{{ 'INTEREST.INTEREST' | translate }}</mat-label>
            <mat-select formControlName="selectedInterests" multiple>
              <mat-option *ngFor="let interest of interests" [value]="interest">
                <!-- {{ interest | translate }} -->
                {{ interest.name }}
              </mat-option>
            </mat-select>
            <mat-error *ngIf="profileData.controls.selectedInterest.hasError('required')">
              {{ 'PROFILE.VALID.INTEREST' | translate }}
            </mat-error>
          </mat-form-field>

PS: I'm using Angular 16


Solution

  • My comment in an answer

    selectedInterests: new FormControl<Interest[]>([], Validators.required)
    

    We can check the docs about typed Forms

    Another way is use some "bizarro" like

    selectedInterests: new FormControl<any>([], Validators.required)
    

    but we loose the capacity of typescript check ours errors