Why is there is no FormArrayDirective in @angular forms?
Asked Answered
I

1

10

According to the latest version of angular, the @angular/forms export the following things:

export {FormControlDirective} from './directives/reactive_directives/form_control_directive';
export {FormControlName} from './directives/reactive_directives/form_control_name';
export {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
export {FormArrayName} from './directives/reactive_directives/form_group_name';
export {FormGroupName} from './directives/reactive_directives/form_group_name';

FormContolName and FormControlDirective, FormGroupName and FormGroupDirective, but FormArrayName with no FormArrayDirective, why?

Instrumentality answered 14/8, 2017 at 8:31 Comment(0)
P
1

I think that it's unnecessary. Well, you can create the directive, some like

@Directive({
  selector: '[formArrayName]'
})
export class FormArrayDirective implements OnInit {
  formArray: FormArray;
  constructor(
    private el: ElementRef,
    @Host() @Optional() public form: FormGroupDirective
  ) {}
  ngOnInit() {
    this.formArray = this.form
      ? (this.form.form.get(
          this.el.nativeElement.getAttribute('formArrayName')
        ) as FormArray)
      : null;
  }
}

Update before in form we has the FormGroupDirective, I think it's better to have the FormGroup

The new Directive

@Directive({
  selector: '[formArrayName]'
})
export class FormArrayDirective implements OnInit {
  formArray: FormArray;
  form:FormGroup;
  constructor(
    private el: ElementRef,
    @Host() @Optional() private formDirective: FormGroupDirective
  ) {}
  ngOnInit() {
    this.formArray = this.formDirective
      ? (this.formDirective.form.get(
          this.el.nativeElement.getAttribute('formArrayName')
        ) as FormArray)
      : null;
      this.form=this.formDirective?this.formDirective.form:null
  }
}

This directive exposes two properties: form and formArray, but be careful, you only can access this properties from a component that has a @ViewChild(FormArrayDirective) in ngAfterViewInit

Curiosity, what is the aim to get it?

Patency answered 25/6, 2021 at 7:4 Comment(1)
Just came across this and while I don't know the aim for the OP - my aim was just to understand why there is a difference. If FormArrayDirective is unnecessary - why is FormGroupDirective necessary ?Amphiboly

© 2022 - 2024 — McMap. All rights reserved.