Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a FormArray as the top level form

I'm using @ngular/core 6.1.1 and @angular/forms 6.1.1

I'm trying to write a ControlValueAccessor which will manage an array of values.

I'm using reactive forms and declaring my form like this:

export class ItemsFormComponent implements ControlValueAccor, OnInit {

    public form: FormArray;

    public items: string[] = ['foo', 'bar', 'baz'];

    constructor(private formBuilder: FormBuilder) {
        this.form = this.formBuilder.array(this.items.map((item) => new FormControl(item)));

        this.form.valueChanges
            .debounceTime(200)
            .subscribe((items: string[]) => {
                this.onChangeFn(items);
            });
    }
}

But then, I get a Template parsing error with

<ol [formArray]="form">
    ...
</ol>

Can't bind to 'formArray' since it isn't a known property of 'ol'

I DID include the FormsModule and the ReactiveFormsModule in my Feature Module. Any other form based on FormGroup work.

It kinda works if I do <ol [formGroup]="form"> but it seems like a weird hack and the validation seems broken. And I'm afraid it will break when building for prod anyway.

So is there no way to use a FormArray as the top level form? Ideally, I'd like to avoid creating a FormGroup with a single FormArray in it.

like image 276
paztek Avatar asked Nov 10 '18 12:11

paztek


1 Answers

Yes you can use FormArray as the top level form,

place: FormArray = new FormArray([
      new FormControl('SF'),
      new FormControl('NY'),
]);

And in the template,

<div *ngFor="let c of place.controls; index as i">
  <input [formControl]="c" placeholder="c">
</div>

<ng-container *ngFor="let c of place.controls">
  <pre>{{this.c.value | json}}</pre>
</ng-container>

Here is the working demo on stackblitz

like image 110
anonymous Avatar answered Sep 19 '22 20:09

anonymous