在编辑组件中设置下拉列表值

问题描述 投票:0回答:1

我有一个带有mat-select下拉列表的编辑表单。当我转到编辑表单时,我想在下拉列表中设置所选项目。为此我调用服务来获取当前值。

我的HTML:

  <mat-form-field appearance="outline">
                  <mat-select formControlName="organisationUnit" placeholder="Organisation Unit" [(value)]="selected">
                    <mat-option *ngFor="let unit of orgUnits" [value]="unit.id" >
                      {{unit.name}}
                    </mat-option>
                  </mat-select>
                </mat-form-field>

我的:

  ngOnInit() {

    this.setupFirstFormGroup();
    this.setupSecondFormGroup();
    this.firstFormGroup.get('status').setValue(true);
    this._route.params.subscribe(params => {
      this.tenantAdminService.getUser(params.id).subscribe(res => {
        this.firstFormGroup.get('first_name').setValue(res['first_name']);
        this.firstFormGroup.get('last_name').setValue(res['last_name']);
        this.tenantAdminService.getOrganizationUnit(res['organizationUnit']).subscribe(res => {
          console.log("ORGUNIT", res);
          this.selected = res['id'];

          this.firstFormGroup.get('organisationUnit').setValue(res['id']);

        });

      });
    });

  }

目前它没有在下拉列表中设置值并且为空。它打印出值,但所选选项不显示为已选中

angular-material angular7
1个回答
0
投票

要预先选择值,您需要将模型绑定到select列表。

<mat-form-field appearance="outline">
      <mat-select [(ngModel)]="your_model_name" formControlName="organisationUnit" placeholder="Organisation Unit" [(value)]="selected">
           <mat-option *ngFor="let unit of orgUnits" [value]="unit.id" >
                {{unit.name}}
           </mat-option>
       </mat-select>
</mat-form-field>

绑定模型并在Component中预设模型中所需的值时,预选值将显示在select列表中。此外,请注意,如果您的下拉值不是字符串,则需要使用[ngValue]="..."而不是[value]="...",因为value仅支持字符串。

所以现在如果我们使用模型myUnit

...
<mat-select [(ngModel)]="myUnit" ...
...

在我们的组件中:

this.myUnit = { ... , id: 1}; // pre-selecting a demo unit object

从我们的下拉单位与unit.id = 1将预选。

如果你收到警告:

看起来您在与formControlName相同的表单字段上使用ngModel。 Angular v6中不推荐支持将ngModel输入属性和ngModelChange事件与反应式表单指令一起使用,并将在Angular v7中删除

然后注意:如果你正在寻找Angular 6文档,那么使用this。参考official docs的贬值,如果我们想要替换它,有三种可能的选择: 1.使用反应形式

// html
<mat-form [formGroup]="form"> ... 
    <mat-select formControlName="organisationUnit"> ...
    ....
</form>
// Component: 
this.form.get('organisationUnit').setValue('your preset value');
  1. 使用模板驱动的表单
  2. 沉默这个警告(不建议使用) 导入:[ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl:'never'}); ]

关于弃用的类似问题之前已经被问过,请参考原始的stackoverflow post以获得评论和答案。我刚刚提供了接受的答案,因为帖子被删除,链接变得过时了。

© www.soinside.com 2019 - 2024. All rights reserved.