简体   繁体   中英

Angular 4 select selected value

I got a problem with select tag in Angular 4. Here's my code.

update.component.html:

<div class="animated fadeIn" *ngIf="organization">
...
     <div class="form-group animated fadeIn" *ngIf="organizationTypes">
          <label for="searchOrgType">Тип організації</label>
          <select [(ngModel)]="organization.organizationType" class="form-control" id="searchOrgType" name="searchOrgType" #searchOrgType="ngModel">
              <option [ngValue]="null">Choose type</option>
              <option *ngFor="let type of organizationTypes" [ngValue]="type">{{type.name}}</option>
          </select>
     </div>

update.component.ts:

 ngOnInit() {
    this.route.params.subscribe(params => {
        this.organizationService
            .getItem(+params['id'])
            .subscribe(
                organization => {
                    this.organization = organization;
                    this.titleService.setTitle('Update - ' + this.organization.name);
                })
    });
    this.getOrganizationTypes();
    this.getTaxTypes();
}

...

private getOrganizationTypes(): void {
    this.organizationTypeService.getList()
        .subscribe(types => this.organizationTypes = types);
}

Getting organization and types lists works ok. So I see all options I need in select list and organization info.

But select value work good only for null values. So if organization.organizationType == null I see "prompt" Choose type value as expected. But if organization type not null I see empty select value. I tried to add [selected] with object and id's comparsions with no effect.

Can anybody help me please? Can't understand what I'm doing wrong.

Try using the compareWith directive

https://angular.io/api/forms/SelectControlValueAccessor#syntax

(example belows assume your objects have a unique id property)

<select [(ngModel)]="organization.organizationType" class="form-control" id="searchOrgType" name="searchOrgType" #searchOrgType="ngModel" [compareWith]="compareFn">
              <option [ngValue]="null">Choose type</option>
              <option *ngFor="let type of organizationTypes" [ngValue]="type">{{type.name}}</option>
          </select>

          compareFn(o1: OrganizationType, o2: OrganizationType): boolean {
            return o1 && o2 ? o1.id === o2.id : o1 === o2;
            }

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