在Chrome中设置选定的Option Angular 4+

时间:2018-09-09 08:05:38

标签: angular

我试图设置从数据库检索并传递到@Input的选项的选定值。该值已正确传递到控件中,但从未设置该选项-默认为第一个值。

import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { ISuburbDto } from '../types';
import { SuburbDataService } from '../venues/suburbs/suburb-data.service';

@Component({
    selector: 'suburbs-list',
    template: ` 
    <select type="text" class="form-control" [(ngModel)]="selected" (ngModelChange)="emit()"   name="suburb" 
    #suburb="ngModel">
    <option *ngFor="let suburb of suburbs" [ngValue]="suburb" [selected]="selected && suburb.id == selected.id">{{suburb.name}}</option>
</select>`
})
export class SuburbsDropDownList implements OnInit {


    public suburbs: Array<ISuburbDto>;

    @Output()
    valueChanged: EventEmitter<ISuburbDto> = new EventEmitter<ISuburbDto>();

    @Input()
    selected: ISuburbDto;

    constructor(private suburbDataService: SuburbDataService) {
        this.suburbs = new Array<ISuburbDto>();

    }

    emit() {
        this.valueChanged.emit(this.selected);
    }

    ngOnInit(): void {
        this.suburbDataService.getAllSuburbs().subscribe(x => this.suburbs = x);
    }

}

有人可以帮忙吗?

欢呼

2 个答案:

答案 0 :(得分:0)

value属性添加到选择中:

<select [value]="suburbs[0]">

答案 1 :(得分:0)

如下更新代码:

<select type="text" class="form-control" [(ngModel)]="selected" [value]="suburbs[0]" (ngModelChange)="emit()" name="suburb" 
    #suburb="ngModel">
    <option *ngFor="let suburb of suburbs" [ngValue]="suburb" [selected]="selected && suburb.id == selected.id">{{suburb.name}}</option>
</select>