Search code examples
angularprimengangular-forms

Primeng Dropdown not binding the options in Angular FormArray


I am trying to bind the primeng dropdown in the Array of form in Angular 7. But the given options are not getting bind.

If am same using out side of form its getting bind. Can you help me to resolve this. what mistake I did in it.

Here is the Code at stackblitz

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


Solution

  • you can try these

    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);
        }  
    }