Primeng Dropdown不绑定Angular FormArray中的选项

时间:2019-07-30 12:44:53

标签: angular primeng angular-forms

我试图绑定Angular 7中的Array数组中的primeng下拉列表。但是给定的选项未绑定。

如果使用相同的格式,则绑定。您能帮我解决这个问题吗?我在其中犯了什么错误。

这是stackblitz上的代码

https://stackblitz.com/edit/angular-form-array-example-d7vksr?file=package.json

1 个答案:

答案 0 :(得分:3)

您可以尝试这些

import { Component } from '@angular/core';
import { FormControl, FormGroup, FormArray, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <form [formGroup]="form">
      <input type="checkbox" formControlName="published"> Published
      <div *ngIf="form.controls.published.value">
        <h2>Credentials</h2>
        <button (click)="addCreds()">Add</button>
        <div formArrayName="credentials" *ngFor="let creds of form.get('credentials').controls; let i = index">
          <ng-container [formGroupName]="i">
            <input placeholder="Username" formControlName="username">
            <input placeholder="Password" formControlName="password">
              <p-dropdown formControlName="car" [options]="cars" placeholder="Select a Brand"></p-dropdown>
          </ng-container>
        </div>
      </div>
    </form>
    <div (click)="formData()"> SUBMIT </div> 
  `,
})
export class AppComponent  {
    form: FormGroup;
    creds :FormArray;
    cars:any[]=[];
    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            published: true,
            credentials: this.fb.array([]),
        });
        this.creds  = this.form.controls.credentials as FormArray
        this.cars = [
            {label: 'Audi', value: 'Audi'},
            {label: 'BMW', value: 'BMW'},
            {label: 'Fiat', value: 'Fiat'},
            {label: 'Ford', value: 'Ford'},
            {label: 'Honda', value: 'Honda'},
            {label: 'Jaguar', value: 'Jaguar'},
            {label: 'Mercedes', value: 'Mercedes'},
            {label: 'Renault', value: 'Renault'},
            {label: 'VW', value: 'VW'},
            {label: 'Volvo', value: 'Volvo'}
        ];
    }

    addCreds() {
        const creds = this.form.controls.credentials as FormArray;
        creds.push(this.fb.group({
            username: '',
            password: '',
            car: []
        }));
    }       

    formData(){
        console.log(this.form.value);
    }  
}