无法以Angular 2形式获取所选项目

时间:2017-08-04 19:05:07

标签: angular angular-forms

我正在学习Angular 2(4),我对Angular表单有点问题。问题是当我在下拉列表中选择该项时,我无法从数据库中检索项的值。因此,在我的情况下,当我在下拉列表中选择“品牌”时,我无法检索“品牌”的值。

这是我的“品牌”型号:

 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>

那么我做错了什么?

编辑: 我试着记录车辆:

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

这就是我得到的: console

我想我应该得到这样的结果:对象{品牌:“1”} 。有人知道可能是什么问题吗?

1 个答案:

答案 0 :(得分:0)

您正在使用ngModel,因此您的change活动将无效,您应该使用ngModelChange来触发事件onBrandChange()而您错过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>