循环中的Mat-select标签为所有下拉列表选择最后一个值作为默认值

时间:2019-09-03 17:09:44

标签: angular angular-material

我有Mat-select标记,与* ngFor循环使用,并为所有下拉列表选择默认值

<div *ngFor="let investment of data.priorInvestmentExperiences; >

      <mat-form-field appearance="outline" class="mat-type">

        <mat-select [(ngModel)]="investment.productTypeCode"
                    formControlName="productTypeCode"
                    class="form-control">
          <mat-option *ngFor="let type of InvestmentTypes "
                      value="{{type.code}}">
            {{type.name}}
          </mat-option>
        </mat-select>
        <mat-label><strong> Investment Type </strong> </mat-label>
        <mat-error *ngIf="f.productTypeCode.errors?.required">
          Investment Type is <strong>required</strong>
        </mat-error>
      </mat-form-field>

如何为Loop中的所有下拉列表获取不同的默认值?  请帮助我找到解决方案。

1 个答案:

答案 0 :(得分:0)

我在stackblitz(https://stackblitz.com/edit/angular-zhbe9o?file=app%2Fselect-overview-example.html)中尝试了以上代码。我可以为不同的选择设置不同的选项。不知道到底是什么问题。我能想到您的代码无法正常工作的原因

即使通过在ngFor循环中创建选择控件,您也为所有选择附加了相同的formcontrol。因此它将绑定相同的默认值到所有选择控件。

也不要同时使用formcontrol和ngmodel。 ngModel的formcontrol替代。检查以下代码,看看是否可以解决问题。如果未创建带有错误scenrio的示例,则将尝试解决

<div *ngFor="let investment of data.priorInvestmentExperiences">
    <mat-form-field appearance=" outline " class="mat-type ">
        <mat-label><strong> Investment Type </strong> </mat-label>
        <mat-select [(value)]="investment.productTypeCode">
            <mat-option *ngFor="let type of InvestmentTypes" [value]=type.code>
                {{type.name}}
            </mat-option>
        </mat-select>
        <mat-error >
          Investment Type is <strong>required</strong>
        </mat-error>
      </mat-form-field>
      </div>
@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  InvestmentTypes = [{
    code: 1, name: 'invesmentType1'
  }, {
    code: 2, name: 'invesmentType2'
  }, {
    code: 3, name: 'invesmentType3'
  }, {
    code: 4, name: 'invesmentType4'
  }]
  data = {
    priorInvestmentExperiences: [{
      productTypeCode: 1
    }, {
      productTypeCode: 2
    }, {
      productTypeCode: 3
    }, {
      productTypeCode: 4
    }]
  }
}