0
我正在学习Angular 2(4),并且我对Angular form有一些问题。问题是当我在下拉列表中选择该项目时,我无法从数据库检索项目的值。所以在我的情况下,当我在下拉列表中选择“品牌”时,我无法检索“品牌”的值。无法获取Angular 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>
那我做错了吗?
编辑: 我试图登录车辆:
onBrandChange(){
console.log("VEHICLE", this.vehicle);
}
,这就是我得到: console
我想我应该得到的东西是这样的:对象{品牌: “1” }。有人知道可能是什么问题吗?
发生了什么事?它怎么不起作用?你看到一个错误? – DeborahK
你得到的错误是什么? – Aravind
当我在下拉列表中选择某个品牌时,我只在控制台中显示''undefined''。 – iantukic