首页 > 解决方案 > 具有初始值的角度选择

问题描述

我想在材料选择中有默认/初始值。我尝试添加 [(value)]=initialValaue ,[value]=initialValue。但它们不起作用。我有我在表中列出的建筑物。而且每栋建筑的翼楼都很少(我把建筑分成几部分,就像在医院里你有不同的建筑部分)。我使用 select do 显示所有建筑物的翅膀,以便用户可以选择他想要的。但我希望在用户选择之前选择默认值。

<mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
                <mat-label>Podzgrada</mat-label>
                <mat-select [(value)]="selectedPod"  [(ngModel)]="is_selected[i]" disableOptionCentering class="mySelectClass">
                  <mat-option *ngFor="let zgrada of getSpecificPodZg(element.key)" [value]="zgrada.key" required >
                    {{zgrada.ime}}
                  </mat-option>
                </mat-select>
              </mat-form-field>

和我的带有函数的 ts 文件

  getSpecificPodZg(zg_idd:String){
  

    this.SpecificPodZg=[];
    this.PodZgrada.forEach((element: any) => {
      if(element.zg_id==zg_idd){
      this.SpecificPodZg.push(element);
      }

    });
    return this.SpecificPodZg;

也试过这个:with [selected]

<mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
                <mat-label>Podzgrada</mat-label>
                <mat-select   [(ngModel)]="is_selected[i]" disableOptionCentering class="mySelectClass">
                  <mat-option *ngFor="let zgrada of getSpecificPodZg(element.key); let i = index" [value]="zgrada.key" [selected]="i===0"  >
                    {{zgrada.ime}}
                  </mat-option>
                </mat-select>
              </mat-form-field

标签: htmlangularformsselectangular-material

解决方案


首先:

[(value)]="selectedPod" 
[(ngModel)]="is_selected[i]"

这些下面是什么?如果我理解正确,您尝试在此处绑定两个不同的变量。在该 mat-option 值指向特定属性[value]="zgrada.key"的基础上,选择值/ngModel 绑定也应该指向相同的属性,否则在初始选择后可能会显示空白。

我建议使用响应式表单来处理 mat-form-fields 中的数据。然后,您可以轻松地订阅 ngOnInit 中的表单更改并输出数据,以便您可以跟踪更改。粗略的示例(您需要将 ReactiveFormsModule 包含到您的模块中,并将相关的导入表单包含到实际组件中):

foo.component.html:

<form [formGroup]="myForm">
  ...
  <mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
    <mat-label>Podzgrada</mat-label>
    <mat-select formControlName="myListField" disableOptionCentering class="mySelectClass">
      <mat-option *ngFor="let zgrada of getSpecificPodZg(element.key)" [value]="zgrada.key" required >
        {{zgrada.ime}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  ...
</form>

foo.component.ts:

myForm: FormGroup;

constructor(private fb: FormBuilder) { }

ngOnInit(): void {
  this.myForm = this.fb.group({
    myListField: initial_value_here // here you put initial value to a select field, needs to be the same as value of option you want to pick; myListField is a formControlName used with mat-select
  });

  // listening to form changes
  this.myForm.valueChanges.subscribe(c => {
    console.log('form changes', c);
  });
}

推荐阅读