【问题标题】:Edit dependent select编辑依赖选择
【发布时间】:2021-03-12 21:44:24
【问题描述】:

我想制作带有依赖选择的编辑表单(例如:国家、州、城市)。仅当我再次选择第一个选项(汽车品牌)时才编辑工作,因为我将事件(更改)与 $event 一起使用。如何在第二个选择字段(汽车型号)中选择默认值?没有点击事件的第一个选择,第二个选择是空白的。

我的代码: 编辑car.component.html

<form #editcarPost="ngForm" (ngSubmit)="updateCar()" [formGroup]="editcarForm">
  <div class="form-group">
    <label for="carbrand_name">Car Brand</label>
    <select class="form-control" id="carbrand_name" formControlName="id_carbrand" (change)="getCarmodel($event)">
   <option *ngFor='let carbrand of carbrands' [value]="carbrand.id_carbrand" >{{carbrand.carbrand_name}}</option>
    </select>
  </div>
  <div class="form-group">
    <label for="carmodel_name">Car Model</label>
    <select class="form-control" id="carmodel_name" formControlName="id_carmodel">
   <option *ngFor='let obj of carmodelArr' [value]="obj.id_carmodel">{{obj.carmodel_name}}</option>
    </select>
  </div>

editcar.component.ts

 ngOnInit() {
    console.log(this.router.snapshot.params.id);
    this.dataService.getCars().subscribe(data => this.cars = data);
    this.dataService.getCarbrands().subscribe(data => this.carbrands = data);
    this.dataService.getEditCar(this.router.snapshot.params.id).subscribe((result)=>{
    this.editcarForm = new FormGroup({
      id_carbrand: new FormControl(result[0].id_carbrand, Validators.required),
      id_carmodel: new FormControl(result[0].id_carmodel, Validators.required),
      production_year: new FormControl(result[0].production_year),
      plate_number: new FormControl(result[0].plate_number),
      vin: new FormControl(result[0].vin),
      colour: new FormControl(result[0].colour),
      description: new FormControl(result[0].description),
    })
  
  })
  }

  getCarmodel(event)
  {
    var obj = {
      id_carbrand: event.target.value,
    }
    this.dataService.getCarbrandByID(obj).subscribe(res=>{
        this.carmodelArr = res;
    })
  }

如何在不点击第一个选择字段的情况下为 event.target.value 或某事设置默认值?

【问题讨论】:

  • 我不确定是什么问题。您想要第二个选择的汽车型号的默认值,而无需更改第一个下拉列表,其中包含汽车品牌的下拉列表? FormGroup 中的id_carmodel: new FormControl(result[0].id_carmodel, Validators.required) 行已经为第二个下拉菜单设置了默认值。我不确定是什么问题。
  • 是的,但是当我刷新页面时,选择车型是空白的。只有当我通过单击再次选择汽车品牌时它才能正常工作

标签: angular typescript forms select


【解决方案1】:

好的,我通过添加带有 id 参数的第二个函数 getCarmodelstart 而不是事件来解决这个问题。在 OnInit 中我添加了“this.getCarmodelstart(result[0].id_carbrand);”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多