首页 > 解决方案 > 如何在 Angular Material 中设置 Dropdwnlist 值

问题描述

如何在编辑时设置下拉列表项的值。

  1. 首先我有BindDropDown(没问题,我已经完成了)
  2. 其次, OnEdit 我想根据来自服务调用的值设置下拉列表 selectecd 值。

我有两个 html 页面,第一页是摘要屏幕,我在表中显示记录列表。第二页是我的城市表格。当我点击表格内的编辑按钮时,它将重定向到第二页,我需要在第二个表单中设置所有值。

对于输入类型文本:我可以设置城市名称、城市代码等。但是对于下拉列表值没有被选中。

component.html


<form #cityform="ngForm">
<mat-select  placeholder="Select Country" disableOptionCentering name="CountryId"   [(ngModel)]="_city.CountryId"  >
<mat-option value="0">--Select Country--</mat-option>
<mat-option *ngFor="let _country of drpcountry" [value]="_country.value" >
                              {{_country.description}}
</mat-option>
</mat-select>
</form>

城市.ts

export class city {
    public CityId: any;
    public CityCode: string;
    public CityName: string;
    public StateId: any;
    public CountryId: any;

}

.ts

        export class AddeditcityComponent implements OnInit {
         _city: city = new city();
        drpcountry:any;
        constructor(){}

        ngOnInit() {
         this.BindDropdown();
         this._city = "services call"
        }
         BindDropdown() {
  this._httpdrp.GetData(mdlcountry).pipe(takeUntil(this._unsubscribeAll)).subscribe(
            data => {
   this.drpcountry = data;
} );
         drpcountry=//Service call;
        }

    }

更新:drpCountry 数组

{CityId: 7, CityCode: "SUR", CityName: "Surat", StateId: 4, CountryId: 2}

标签: angularangular-materialangular7

解决方案


我会使用异步管道。

<form #cityform="ngForm">
  <mat-select  placeholder="Select Country" disableOptionCentering name="CountryId"   [(ngModel)]="city.CountryId"  >
  <mat-option value="0">--Select Country--</mat-option>
  <mat-option *ngFor="let country of (drpcountry | async)?.drpcountry" [value]="country.value" >
                                {{country.description}}
  </mat-option>
  </mat-select>
  </form>
  BindDropdown() {
    this.drpcountry = // A service that returns an observable
    /*
       Something like this
       listCity(): Observable<City[]> {
         return this.http.get<City[]>(this.url);
       }
    */
   }

该行允许在获得城市列表后显示。

*ngFor="let country of (drpcountry | async)?.drpcountry"

推荐阅读