简体   繁体   中英

selected attribute is not working on <option> - ANGULAR

I'm working with dropdowns and select2, and I need to edit product, and ofcourse that selected product contains a belonging group/category in a dropdown, but that group is not selected when I open modal, even if value is there, here is how I tried to achieve it:

1.) Fill dropdown with all categories (it works) ( *ngFor="let category of mainGroups )

2.) Select corresponding value based on selected article (it doesnt work)

<!--category-->
<div class="form-category">
  <label class="control-label dash-control-label col-xs-3">Product category:</label>
  <div class="col-xs-9">
    <select touch-enter-directive [ref]="ref" [nextFocusElement]="articleSubGroup" id="mainGroupSelectEdit" class="form-control dash-form-control select2" style="width: 100%;"
            data-minimum-results-for-search="Infinity" name="mainGroupSelectEdit" required (change)="filterSubById(article.groupId)" [(ngModel)]="article.groupId">
      <option disabled>-/-</option>
      <option [value]="category.id" *ngFor="let category of mainGroups" [selected]="category.id==='a0e25215-a60e-4444-b6ac-4521b7de4b37'">{{category.title}}</option>
    </select>
    {{article.mainGroup.id}} <- here is shown value a0e25215-a60e-4444-b6ac-4521b7de4b37, so I thought that value should be selected in dropdown
  </div>
</div>

As you can see guys I've used

[selected]="category.id==='a0e25215-a60e-4444-b6ac-4521b7de4b37'"

because I thought this might work like this, but obliviously it can not..

You have the model of the select set to article.groupId .

It doesn't matter if you use [selected] as long as the article.groupId remains unchanged.

If you want the option a0e25215-a60e-4444-b6ac-4521b7de4b37 to be selected, you need to assign the a0e25215-a60e-4444-b6ac-4521b7de4b37 value to the article.groupId property. In this case the ngModel sets the selected attribute as long as it's value is equal to one of the options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM