首页 文章

角度预选选择输入

提问于
浏览
0

我有一个FormGroup,其中包含2个FormControls“name”和“type” . Type是一个select html输入,其中包含使用ngFor循环生成的选项 . 所以当我编辑我的元素时,带有FormGroup的Component出现,它会加载我想要编辑的元素,并在名称输入字段中自动填充元素的名称 . 我想要做的是与类型字段相同 .

mycomponent.html

<form [formGroup]="myForm" (ngSubmit)="onMyFunktion()">
  <div class = "form-group">
      <label for="name">Name</label>
      <input formControlName="name" type="text" id="name" class="form-control" required >
  </div>
  <div class="form-group">
    <label for="type">Type</label>
    <select formControlName="type" id="type" class="form-control"  required >
      <option *ngFor="let Type of types" value="Type.Id">{{Type.Name}}</option>
    </select>
  </div> 
  <button type="submit" [disabled]="!MyForm.valid"  class ="btn btn-primary">save</button>
  <button type="button" (click)="onBack()" class ="btn btn-success">Back</button>
</form>

mycomponent.ts

ngOnInit()
  {
  this.MyForm = new FormGroup
  ({
    name: new FormControl(this.myElement.Name), 
    type: new FormControl() // myElement only has its Name and the Id of the type not the type name
  })
 }

1 回答

  • 0

    当您处理对象时,angular无法自动检测默认值,因此您必须添加 compareWith 属性,如下所示:

    <select formControlName="type" id="type" class="form-control"  required [compareWith]="byTypeId" >
    

    在你的组件类中,你必须编写这样的byTypeId方法:

    byTypeId(a, b) {
      return a === parseInt(b, 10);
    }
    

    PS: I am supposing that your type id is an integer

相关问题