【问题标题】:pre-selected option ( Dropdown ) for Edit form in angular6angular6中编辑表单的预选选项(下拉)
【发布时间】:2019-01-10 18:21:03
【问题描述】:

我在我的站点中为添加类别创建了一个编辑表单。

我需要在进入编辑页面时为下拉菜单选择类别值。

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- 向服务器发送请求以获取类别列表以填充下拉列表。

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

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>

我现在需要为数据库中的类别选择存在的值并在下拉列表中选择该值。

我该怎么做?

【问题讨论】:

  • this.selectedCat,是不是和options中使用的cat.id同类型?
  • @Aragorn 是的。他们都是number
  • 第一个错误是你不需要同时使用 formcontrol 和 ngModel。请使用其中任何一种。
  • 对于列表中的选择下拉菜单,我建议您查看并尝试此模块。这对你很有帮助,也很容易。 ngx-select-dropdown
  • @SachinShah 你能帮我吗?

标签: javascript angular typescript angular6


【解决方案1】:

当用于options 列表的数组包含复杂对象而不仅仅是stringnumber,则需要使用ngValue。 试试这个:

更新:添加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>

在您的组件中:

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

如果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: '    دسته اصلی '});
  })
 }

【讨论】:

  • @kianoush 你可以为此创建一个 stackblitz 页面吗?
  • 好的,试试这个文档,可能对你有帮助:medium.com/@kastepanyan24/…
  • 我是伊朗人。这个网站过滤我的国家。和我的国家过滤所有的 vpn :)))))
  • 更新了我的答案以使用 compareWith 函数,试试吧。
  • 谢谢人。它的工作,但几乎没有问题。当我需要选择这个时:&lt;option &gt; دسته اصلی &lt;/option&gt; 它不显示任何东西。当类别 id 是 0 我需要选择这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多