简体   繁体   English

在Angular中使用ngFor预选下拉指令选项

[英]Preselect option for dropdown directive with ngFor in Angular

I created a directive for my angular project which makes a request to a backend API to fetch a number of countries and then populates the options of a selector with an ngFor. 我为我的角度项目创建了一个指令,该指令向后端API发出请求以获取许多国家/地区,然后使用ngFor填充选择器的选项。 Below you can see how they are structured: 您可以在下面看到它们的结构:

select.component.html: 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 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 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);
            });
        }
    }
}

When a country is selected, an event is emitted and the whole application updates itself with the new value. 选择国家/地区后,将发出一个事件,整个应用程序将使用新值更新自身。

My question is, how can I have the value that the user has chosen preselected, perhaps after when they refresh the page? 我的问题是,我怎样才能获得用户选择的预选值,也许是在刷新页面之后? I tried to pass in the preselected value as an input to the component, as you can see in the .html file, but the selector is still blank, until the user chooses a new value. 我试图将预选值作为组件的输入传递,如.html文件中所示,但选择器仍为空,直到用户选择新值。

This might be a very crude way of doing it: 这可能是一种非常粗糙的方式:

<select id="countrySelector" class="form-control" [(ngModel)]='coutryOption' (ngModelChange)='countrySelected($event)' required>
    <ng-container *ngFor="let country of countriesList;">
        <ng-container *ngIf="country.name === countryToDisplay">
            <option [ngValue]=country selected>{{country.name}}
            </option>
        </ng-container>
        <ng-container *ngIf="country.name !== countryToDisplay">
            <option [ngValue]=country>{{country.name}}
            </option>
        </ng-container>
    </ng-container>
</select>

Similar to the @Praveen Kumar answer but what I use if it helps any: 类似于@Praveen Kumar的答案,但是如果有帮助,我会使用它:

<select class="form-control" [(ngModel)]="countryOption">
   <ng-template [ngIf]="select">
      <option value=''>{{select}}</option>
      <option *ngFor="let country of countryList" type="text" [ngValue]="country.name">{{country.name}}</option>
   </ng-template>
   <ng-template [ngIf]="!select">
      <option *ngFor="let country of countryList" type="text" [ngValue]="country.name">{{country.name}}</option>
   </ng-template>
</select>

After fiddling around with the select form, it turned out that the [(ngModel)]='coutryOption' was not set to anything in on init. 在摆弄了选择形式之后,结果发现[(ngModel)] ='coutryOption'没有设置为初始化中的任何内容。

So i change the component to look like so: 所以我改变组件看起来像这样:

export class CountrySelectorComponent {
@Input('countryToDisplay') countryToDisplay: string;
@Output() shippingCountryChanged: EventEmitter<string> = new EventEmitter();
countriesList: Object[];
countryOption: object;
constructor () { }

populateCountriesList(countries) {
    this.countriesList = countries;
    this.countryOption = this.countriesList.filter(country => {
        return country['name'] === this.countryToDisplay
    });
    this.countryOption = this.countryOption[0];
}
countrySelected(e) {
    this.shippingCountryChanged.emit(e);
 }
}

and the html looks like so: 并且html看起来像这样:

<div class="col-sm-10" (countriesFetched)="populateCountriesList($event)" appGetCountriesList>
    <select id="countrySelector" class="form-control" [(ngModel)]='countryOption' (ngModelChange)='countrySelected($event)' required>
        <option *ngFor="let country of countriesList;"  [ngValue]=country >{{country.name}}</option>
    </select>
</div>

This works for its' intended purpose. 这适用于其“预期目的”。 Thank you for you answers! 谢谢你的答案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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