1

Can anyone tell me how I can set the initial value of the below select? I have tried doing this through my formControl and although the value in the form will be correct it is not reflected within the view

HTML :

<mat-form-field>
 <mat-select name="animationType" formControlName="animationType" 
  placeholder="select animation">

  <mat-option *ngFor="let type of animationTypes" [value]="type">
   {{type.name}}
  </mat-option>

 </mat-select>
</mat-form-field>

TS :

  animationTypes = [
    { name: 'balloon' },
    { name: 'kite' },
    { name: 'wolf' }
  ];
0

2 Answers 2

1

I see you have used formControlName, So You can set default value directly from TS file like following :

HTML :

<mat-form-field>
    <mat-select name="animationType" formControlName="animationType" placeholder="select animation">
        <mat-option *ngFor="let type of animationTypes" [value]="type">
            {{type.name}}
        </mat-option>
    </mat-select>
    <mat-error *ngIf="poemForm.controls.animationType.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>

TS :

  ngOnInit() {
    this.poemForm.patchValue({ 
      animationType: selectedAnimationType // Selected Value E.g. this.animationTypes[0]
    });
  }
Sign up to request clarification or add additional context in comments.

4 Comments

this updates the formControl value but in the view the select input still displays the placeholder as if it has no value yet and nothing has been selected. What I need is for the select input to display the value that has been set in the formControl,
You are using [value]="type" as object. So in selectedAnimationType you will need to add object only. Like this.animationTypes[0]
Or try using [value]="type.value" and use selectedAnimationType = {some string value existing in array object}. I think this is the issue.
neither of these worked, I think you maybe correct that is has something to do with the fact that [value]="type" is an object (i updated the original post with my objects) but I also made selectedAnimationType an object like this { name: "some string" } to match the orginal objects being passed into the ngFor loop but it still did not update the select in the view
0

Seems the only solution I found was to plug an ngModel on the select like so.

<mat-form-field>
 <mat-select name="animationType" formControlName="animationType" 
  placeholder="select animation" [(ngModel)]="selectedAnimType">

  <mat-option *ngFor="let type of animationTypes" [value]="type.name">
   {{type.name}}
  </mat-option>
 </mat-select>
 <mat-error *ngIf="poemForm.controls.animationType.invalid">{{getErrorMessage()} 
 </mat-error>
</mat-form-field>

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.