简体   繁体   English

在angular6中为“编辑”表单预先选择的选项(“下拉”)

[英]pre-selected option ( Dropdown ) for Edit form in angular6

i create a edit form for add-category in my site . 我在我的网站中为添加类别创建了一个编辑表单。

i need when enter the edit page it selected category value for dropdown . 我需要在进入编辑页面时选择下拉列表的类别值。

1 - i send the request to server for get detail : 1-我将请求发送到服务器以获取详细信息:

  public GetCatDetail(id:number){
    this.catService.GetCatDetail(id).subscribe((data)=>{
    this.cat=data,
    this.editCatFG.setValue({
      pFaName:[data.pFaName],
      pEnName:[data.pEnName],
      subCat:[data.subCat]
    }),
    this.selectedCat=data.subCat
  })
  }

2- send a request to server for get category list to fill dropdown . 2-向服务器发送请求以获取类别列表以填充下拉列表。

 public GetAllCat(){
  this.catService.GetAllCatList().subscribe((data)=>{
  this.cats=data
  })
 }

3- i fill the dropdown in html : 3-我在html中填写下拉列表:

    <select style="margin-right: 105px;" name="roleLevel" formControlName="subCat" [(ngModel)]="selectedCat">
                    <option  selected>    دسته اصلی </option>
                    <option *ngFor="let cat of cats" selectedCat="cat.id" [value]="cat.id" >{{cat.pFaName}}</option>
     </select>

I now need to select the value that exists for the categories in the databaseand selected that in the form in the dropdown. 现在,我需要选择数据库中类别所存在的值,并在下拉列表中的表单中进行选择。

how can i do this ? 我怎样才能做到这一点 ?

When the array used for options list is of complex objects than just string or number , you need to use ngValue . 如果用于options列表的数组是复杂的对象,而不仅仅是stringnumber ,则需要使用ngValue Try this: 尝试这个:

Update: Adding compareWith to select the default value 更新:添加compareWith以选择默认值

<select style="margin-right: 105px;" name="roleLevel" formControlName="subCat" [(ngModel)]="selectedCat" [compareWith]="compareById">
                    <option *ngFor="let cat of cats"  [ngValue]="cat" >{{cat.pFaName}}</option>
     </select>

In your component: 在您的组件中:

compareById(o1, o2) {
    return o1.id === o2.id
  }

If cat.id = 0 is not coming from the service, you can add it to the array like this: 如果cat.id = 0不是来自服务,则可以将其添加到数组中,如下所示:

public GetAllCat(){
  this.catService.GetAllCatList().subscribe((data)=>{
  this.cats=data
  //adding the value for id=0;
  this.cats.push({id:0, pFaName: '    دسته اصلی '});
  })
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM