首页 文章

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

提问于
浏览
3

我为我的角度项目创建了一个指令,该指令向后端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 回答

  • 1

    这可能是一种非常粗糙的方式:

    <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>
    
  • 1

    类似于@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>
    
  • 1

    在摆弄了选择形式之后,结果发现[(ngModel)] ='coutryOption'没有设置为初始化中的任何内容 .

    所以我改变组件看起来像这样:

    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);
     }
    }
    

    并且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>
    

    这适用于其“预期目的” . 谢谢你的答案!

相关问题