Angular 已选择 2 套 属性

Angular 2 set selected property

我正在尝试在 Angular2 中设置 selected 选项。

我有一个select。

<select class="form-control" id="country"  [(ngModel)]="facility.country"  formControlName="countryField" (ngModelChange)="countrySelected($event)" >
     <option id="countryOption{{c.id}}" *ngFor="let c of rawCountries" [ngValue]="c">{{c.message}}</option>
</select>

以及 select 方法。

countrySelected(): void {
   this.facility.country = this.rawCountries.find(rawCountries => rawCountries.name === this.facility.country.name);
}

我的注册分为 2 个步骤,由 2 个不同的组件表示。这个select是在注册的第一步。用户可以选择 return 在完成后返回到第一步。我在第一步中做出他 selected 的选项时遇到问题,再次 selected。它变回默认选项和我的模型。

我试过这个解决方案,但它不起作用。

<option id="countryOption{{c.id}}" [selected]="facility.country && (facility.country.id==c.id)" *ngFor="let c of rawCountries" [ngValue]="c">{{c.message}}</option>

有什么让它发挥作用的想法吗?

(ngModelChange)="countrySelected($event) just does again what [(ngModel)]="facility.country" 已经做了。

当您向后导航时,您需要将 facility.country(在代码中)设置为用户选择的值。您需要将其存储在某处(共享服务或类似服务)才能获得用户之前选择的值。