数组值returng索引:值

时间:2018-07-01 23:15:14

标签: angular

我有一个要调用的状态数组,它返回一个带编号的数组,而不是对象的平面数组(至少根据我的观察)。

我的数组

[
    {_id: 1, abbr: 'AL', name: 'Alabama', country: 'USA' },
    {_id: 2, abbr: 'AK', name: 'Alaska', country: 'USA' },
    {_id: 3, abbr: 'AZ', name: 'Arizona', country: 'USA' },
]

控制台记录的内容(以及导致我选择的问题所在)。

[
    0:{_id: 1, abbr: "AL", name: "Alabama", country: "USA"},
    1:{_id: 2, abbr: "AK", name: "Alaska", country: "USA"},
    2:{_id: 3, abbr: "AZ", name: "Arizona", country: "USA"},
]

我的角度选择看起来像这样,因为在这种情况下,我想将“名称”作为值传递...

<option *ngFor="let state of states" [ngValue]="state.name">{{state.name}}</option>

但这是通过

1: Alaska

感谢您的帮助。

似乎我在2月有这个问题-ngValue returning index and value-但是这些解决方案无法解决我当前的问题。

我正在添加更多上下文,以期寻求解决方案。 谢谢

代码:

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { LocationService } from '../../services/location.service';

@Component({
    selector: 'app-myState',
    template: ` <form 
        novalidate="novalidate" 
        autocomplete="off" 
        [formGroup]="form" 
        (ngSubmit)="submitForm()">

        <label>State</label>
        <select class="form-control "   
            (change)="changeMyState($event)"
            name="mystate" 
            formControlName="mystate" >
            <option *ngFor="let state of states" [ngValue]="state.name">{{state.name}}</option>
        </select>

    </form>`
})

export class myComponent implements OnInit {

    mystate: string;
    states: any[];

    form: FormGroup;
    model = new myStateModel({});
    submitAttempted = false;
    loading = false;

    constructor(
        private location: LocationService
    ) { }

    get formDisabled() {
        return this.loading === true;
    }

    get formModel() {
        return {
            mystate: this.form.get('mystate').value,
        };
    }

    ngOnInit() {
        this.states = this.location.getStates(); // this is the states array        
        this.form = new FormGroup({
            mystate: new FormControl()
        });
    }

    changeCollegeState(e) {
        console.log(e.target.value); // this is the 0: Alabama ... return value...should be 'Alabama' without the index:        
    }

    resetForm() {
        this.form.get('mystate').markAsUntouched();
        this.submitAttempted = false;
    }

    submitForm() {
        this.loading = true;
        ...
    }

    showError(fieldName: string) {
        ...
    }

}

0 个答案:

没有答案