Построение выпадающего / выбор динамически через реактивные формы угловые 6 - PullRequest
0 голосов
/ 24 августа 2018

У меня есть несколько (любое количество) выпадающих в форме, которые мне нужно построить динамически.

Все они должны иметь выбранное значение, поэтому необходимо применить требуемый валидатор.

Пример json

  [
    {
      "FeatureCaption": "Style",
      "SelectedValue": "shaker",
      "FeatureList": [
        {
          "FeatureId": "CHOOSE",
          "FeatureName": "Choose",
          "IsSelected": true
        },
        {
          "FeatureId": "shaker",
          "FeatureName": "Shaker",
          "IsSelected": false
        }
      ]
    },
    {
      "FeatureCaption": "Material",
      "SelectedValue": "std",
      "FeatureList": [
        {
          "FeatureId": "CHOOSE",
          "FeatureName": "Choose",
          "IsSelected": true
        },
        {
          "FeatureId": "std",
          "FeatureName": "Standard",
          "IsSelected": false
        }
      ]
    }
  ]

Эти функции доступны в форме через this.features

Код компонента для получения данных и построения формы

  onInit() {

    //init form, so angular will complain about formgroup since template is going first
    this.inItForm();

    this.dataSubscription = this.projectSubService.getProjectSubConfig(this.subId).subscribe(
      res => {
        this.features = res.Features;

        //push in features
        this.pushInFormFeatures();
      },
      error => {
        //do error handling part...
      }
    );

  }

метод inItForm

  inItForm() {
    //will be putting the config as FormArray
    let configFeatures = new FormArray([]);

    //loop through the features and push into configFeatures FormArray above
    //this.features.forEach(i =>
    //  configFeatures.push(
    //    new FormGroup({
    //      'config': new FormControl({ value: i.SelectedValue, options: i.FeatureList, label: i.FeatureCaption }, Validators.required)
    //    })
    //  )
    //);

    //now create the main FormGroup and add config features to it
    this.projectForm = new FormGroup({
      'features': configFeatures
    });
  }

Метод Push в формах

  pushInFormFeatures() {
    this.features.forEach(i =>
      (<FormArray>this.projectForm.get('features')).push(
        new FormGroup({
          'config': new FormControl({ value: i.SelectedValue, options: i.FeatureList, label: i.FeatureCaption }, Validators.required)
        })
      )
    );
  }

и html

  <form [formGroup]="projectForm" (ngSubmit)="onSubmit()">

      <div class="form-row">
        <div class="col">

          <div formArrayName="features">

            <div class="form-group form-row" *ngFor="let ic of projectForm.get('features'); let i=index;" [formGroupName]="i">
              <div class="col-lg-2 text-right"><label for="{{i}}" class="col-form-label">{{ic.label}} <app-required-star></app-required-star></label></div>
              <div class="col-lg-10">
                <select class="form-control" id="{{i}}" formControlName="config" [appAutoFocus]="">
                  <!--<option *ngFor="let op of ic.options" [value]="op.FeatureId">{{op.FeatureName}}</option>-->
                </select>
                <!--<span class="mwk-validation-error form-text" *ngIf="!projectForm.get('features')[{{i}}].valid && projectForm.get('features')[{{i}}].errors?.required">Required</span>-->
              </div>
            </div>

          </div>

        </div>
     </div>


    <button type="submit" class="btn btn-primary btn-sm">Submit</button>

  </form>

Я получаю следующую ошибку

    ERROR Error: "Cannot find a differ supporting object '[object Object]' 
of type 'object'. NgFor only supports binding to Iterables such as Arrays."

Очевидно, что я неправильно строю массив массива, включая опции выбора.

Как я могу построить что-то подобное?Я искал пример и не смог найти его для использования.

Обновление 1

Пока что используется шаблонный подход, пока я не пойму, как это сделать выше

  <form (ngSubmit)="onSubmit(f)" #f="ngForm">

    <div class="form-group form-row" *ngFor="let f of features; let i=index;">
      <div class="col-lg-2 text-right"><label for="{{f.FeatureId}}" class="col-form-label">{{f.FeatureCaption}} <app-required-star></app-required-star></label></div>
      <div class="col-lg-10">
        <!--custom-select-->
        <select class="form-control" id="{{f.FeatureId}}" name="{{f.FeatureId}}" [appAutoFocus]="i === 0" ngModel required>
          <option  value="" selected>Choose...</option>
          <option *ngFor="let fl of f.FeatureList" [value]="fl.FeatureId" [selected]="fl.IsSelected">{{fl.FeatureName}}</option>
        </select>
      </div>
    </div>


    <div class="row mt-2">
      <div class="col-lg-2 text-right">&nbsp;</div>
      <div class="col-lg-10">

        <button type="submit" class="btn btn-primary btn-sm" [disabled]="!f.valid">Submit</button>

      </div>
    </div>

  </form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...