2017-08-04 4 views
0

私は角2(4)を学んでいますが、角の形には少し問題があります。問題は、ドロップダウンリストでそのアイテムを選択すると、データベースからアイテムの値を取得できないということです。だから私の場合、ドロップダウンリストで "ブランド"を選択すると、 "ブランド"の値を取得できません。選択したアイテムを角2の形にすることはできません

これは私の "ブランド" のモデルである:

public class Brand 
{ 
    [Required] 
    public int BrandId { get; set; } 
    [Required] 
    [StringLength(255)] 
    public string Name { get; set; } 
    public string Description { get; set; } 

    //Relation 
    public virtual ICollection<Car> Cars { get; set; } 

    public Brand() 
    { 
     Cars = new Collection<Car>();collection 
    } 
} 

これは私のコントローラである:

 [HttpGet("/api/brands")] 
    public async Task<IEnumerable<BrandResource>> GetBrands() 
    { 
     var brands = await context.Brands.Include(m => m.Cars).ToListAsync(); 
     return mapper.Map<List<Brand>, List<BrandResource>>(brands); 
    } 

マイマッピングプロファイル:

public MappingProfile() 
    { 
     CreateMap<Brand, BrandResource>(); 
     CreateMap<CarType, CarTypeResource>(); 
     CreateMap<Car, CarResource>(); 
    } 

ブランドを取得するための私のサービス:

@Injectable() 
export class VehicleService { 

constructor(private http: Http) { } 

getBrands(){ 
return this.http.get('/api/brands') 
.map(res => res.json()); 
} 

} 

私が選択したブランドの価値ログインしようとした私のコンポーネント:

@Component({ 
selector: 'app-vehicle-form', 
templateUrl: './vehicle-form.component.html', 
styleUrls: ['./vehicle-form.component.css'] 
}) 
export class VehicleFormComponent implements OnInit { 

constructor(
private vehicleService: VehicleService) { } 
brands: any[]; 
cars: any[]; 
cartypes: any[]; 
vehicle: any = {}; 

ngOnInit() { 
this.vehicleService.getBrands().subscribe(brands => 
    this.brands = brands 

); 

} 

onBrandChange(){ 
var selectedBrand = this.brands.find(b => b.BrandId == this.vehicle.brand); 
    console.log(selectedBrand); 

} 
} 

そして最後に、私のフォームを:

<form> 
<div class="form-group"> 
<label for="brand">Brand</label> 
<select id="brand" class="form-control" (change)="onBrandChange()" [(ngModel)]="vehicle.brand" name="brand"> 
    <option value=""></option> 
    <option *ngFor="let b of brands" value="{{ b.BrandId }}">{{ b.name }}</option> 
</select> 
</div> 
</form> 

だから私は間違って何をやっていますか?

EDIT: 私は車をログに記録しようとした:

onBrandChange(){ 
    console.log("VEHICLE", this.vehicle); 
    } 

、これは私が得るものです: console

私はこのような何かを得る必要があると思う:オブジェクト{ブランド: "1" を}。誰が問題になるかも知っていますか?

+0

が欠落しているngModelはので、あなたのchangeイベントは動作しません使用していますか?どのように動作していないのですか?エラーが表示されますか? – DeborahK

+0

あなたは何を得ていますか? – Aravind

+0

ドロップダウンリストでブランドを選択すると、私のコンソールに「未定義」と表示されます。 – iantukic

答えて

0

あなたがイベントonBrandChange()をトリガーするngModelChangeを使用しなければならないとあなたは何が起こっているngValue

<select id="brand" class="form-control" (ngModelChange)="onBrandChange()" 
     [(ngModel)]="vehicle.brand" name="brand"> 
    <option value=""></option> 
    <option *ngFor="let b of brands" ngValue="{{ b.BrandId }}">{{ b.name }}</option> 
</select> 
関連する問題