我为我的角度项目创建了一个指令,该指令向后端API发出请求以获取许多国家/地区,然后使用ngFor填充选择器的选项 . 您可以在下面看到它们的结构:
select.component.html:
<div class="col-sm-10" (countriesFetched)="populateCountriesList($event)" appGetCountriesList>
<select id="countrySelector" class="form-control" [(ngModel)]='coutryOption' (ngModelChange)='countrySelected($event)' required>
<option *ngFor="let country of countriesList;" [ngValue]=country [selected]="country.name === countryToDisplay? selected:null">{{country.name}}</option>
</select>
</div>
select.component.ts
@Component({
selector: 'app-selector',
templateUrl: './selector.component.html',
styleUrls: ['./selector.component.scss'],
})
export class SelectorComponent implements OnInit {
@Input('countryToDisplay') countryToDisplay: string
@Output() shippingCountryChanged: EventEmitter<string> = new EventEmitter();
countriesList: Object[];
singleCountry: boolean;
constructor () { }
ngOnInit() {
this.singleCountry = false;
}
populateCountriesList(countries) {
this.countriesList = countries;
}
countrySelected(e) {
this.shippingCountryChanged.emit(e);
}
}
selector.directive.ts
@Directive({
selector: '[appGetCountriesList]'
})
export class DropdownDirective {
@Output() countriesFetched = new EventEmitter<any>();
countrylist: Object[] = [];
constructor ( private countriesService: CountriesService ) {
this.getCountries();
}
getCountries() {
if (this.countrylist.length === 0) {
const market = localStorage.getItem('marketCode');
this.countriesService.fetchCountries(market).subscribe( res => {
res = res['countries'];
Object.keys(res).map( key => {
if ( res[key].name.length > 0 && parseInt(res[key].is_enabled, 10) === 1) {
this.countrylist.push(res[key]);
}
});
this.countrylist = this.countrylist.sort();
this.countriesFetched.emit(this.countrylist);
});
}
}
}
选择国家/地区后,将发出一个事件,整个应用程序将使用新值更新自身 .
我的问题是,我怎样才能获得用户选择的预选值,也许是在他们刷新页面之后?我试图将预选值作为组件的输入传递,如.html文件中所示,但选择器仍为空,直到用户选择新值 .
3 回答
这可能是一种非常粗糙的方式:
类似于@Praveen Kumar的答案,但是如果有帮助,我会使用它:
在摆弄了选择形式之后,结果发现[(ngModel)] ='coutryOption'没有设置为初始化中的任何内容 .
所以我改变组件看起来像这样:
并且html看起来像这样:
这适用于其“预期目的” . 谢谢你的答案!