Невозможно отобразить выпадающие значения с помощью Angular 5 - PullRequest
0 голосов
/ 27 апреля 2018

Я новичок в Angular 5 и работаю над учебником. Поражен отображением выпадающих значений в форме. Компонент component.html, показанный ниже, не отображает выпадающие значения. Вот что я попробовал. Любая помощь для устранения этой ошибки высоко ценится.

model.ts:

export class State {

    constructor(public code: number, public description: string) { }
  }

service.ts:

import { Injectable } from '@angular/core';

import { State } from '../shared/prediction-input.model';

@Injectable()
export class GenericService {
   getStates(): State[] {
      let states = [
         new State(1, 'CA'),
         new State(2 , 'TX'),
         new State(3 , 'IL'),
         new State(4 , 'WI')
      ]  
      return states;      
   }


} 

component.html:

Select Vehicle Owner State: 



 <select name="State" [(ngModel)]="State" >
                            <option [ngValue]="null" disabled>Choose Vehicle owner State</option>
                            <option *ngFor="let s1 of allStates" [ngValue]="s1.code">
                                {{ s1.code }}
                              </option>


                    </select>

component.ts:

ngOnInit() {
      this.allStates = this.genericService.getStates();
    console.log("State Code : " + this.allStates[0].code);
    console.log("Description Code : " + this.allStates[0].description);
  }

Ответы [ 2 ]

0 голосов
/ 27 апреля 2018

Не уверен насчет проблемы, с которой вы столкнулись, но вот работающий стек

https://stackblitz.com/edit/angular4-dm5bd2?file=app/app.module.ts

  1. Услуги

import { Injectable } from '@angular/core';

import { State } from './State';

@Injectable()
export class GenericService {
   getStates(): State[] {
      let states = [
         new State(1, 'CA'),
         new State(2 , 'TX'),
         new State(3 , 'IL'),
         new State(4 , 'WI')
      ]  
      return states;      
   }
} 
  1. Модель

export class State {
    constructor(public code: number, public description: string) { }
  }
  1. Шаблон компонента

<hello name="{{ name }}"></hello>
<p>
	<select name="State" [(ngModel)]="State">
                            <option [ngValue]="null" disabled>Choose Vehicle owner State</option>
                            <option *ngFor="let s1 of allStates" [ngValue]="s1.code">
                                {{ s1.code }}
                              </option>


                    </select>
</p>
  1. Класс компонентов

import { Component, OnInit } from '@angular/core';
import { GenericService } from './GenericService';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular 4';
  public allStates: any[] = [];
  public State: any;

  constructor(private genericService: GenericService) {

  }

  ngOnInit() {
    this.allStates = this.genericService.getStates();
    console.log("State Code : " + this.allStates[0].code);
    console.log("Description Code : " + this.allStates[0].description);
  }
}
  1. Модуль приложения: Вы должны зарегистрировать GenericService у провайдеров.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { GenericService } from './GenericService';

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers:[GenericService]
})
export class AppModule { }
0 голосов
/ 27 апреля 2018

Попробуйте, пожалуйста:

Шаг 1: Состояние класса:

export class State{
   constructor(public code: number, public description: string) {}
}

Шаг 2: в service.ts

export class Service {
      private state: State[] = [
         new State(1, 'CA'),
         new State(2 , 'TX'),
         new State(3 , 'IL'),
         new State(4 , 'WI')
       ];
      constructor() { }

      getData() {
        return this.state;
      }
    }

Шаг 3: В component.ts

export class AppComponent {
  public state: State[] = [];
  constructor(public service: Service) {
  }
  ngOnInit() {
        this.state = this.service.getData();
    }
 }

Шаг 4. Компонент html

<div *ngFor="let item of state;let i = index">
    {{item.code}}
    {{item.description}}
</div>

или

<select name="State">
 <option [ngValue]="null" disabled>Choose Vehicle owner State</option>
 <option *ngFor="let item of state;let i = index" >
   {{item.code}}
   {{item.description}}
  </option>
  </select>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...