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

Preselected Element when using *ngFor

I have following Code which will not select a Element, when loading the Component.

 <option  (click)="getSelectdDropdown(1, 'Python'); addNewItemFramework(1); checkForm()" [selected]="this.formGroup.controls['frameworkControl'].value=='1'">Python</option>
            <option (click)="getSelectdDropdown(2, 'Ruby'); addNewItemFramework(2); checkForm()" [selected]="this.formGroup.controls['frameworkControl'].value=='2'">Ruby</option>
            <option (click)="getSelectdDropdown(3, 'C#'); addNewItemFramework(3); checkForm()" [selected]="this.formGroup.controls['frameworkControl'].value=='3'">C#</option>

enter image description here

When I use *ngFor It always select the first Element. How should be the Code with ngFor?

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

<option *ngFor="let title of frameworkArray" >{{title}} {{this.frameworkArray.indexOf(title)}}</option>

The Framework Array is filled in the TypeScript Code.
So there are Elements in it

enter image description here

>Solution :

That’s not how you’re supposed to approach this.

You’re supposed to have a form control tied to your select, and angular will do anything by itself.

Here is an example : https://stackblitz.com/edit/angular-ivy-cke8ps?file=src%2Fapp%2Fapp.component.ts

export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  options = [
    { value: 0, label: 'Javascript' },
    { value: 1, label: 'Rust' },
    { value: 2, label: 'Python' },
    { value: 3, label: 'Golang' },
  ];

  control = new FormControl(this.options[0].value);
}
Choose language :
<select [formControl]="control" placeholder="language">
  <option *ngFor="let option of options" [value]="option.value">
    {{ option.label }}
  </option>
</select>

enter image description here

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