Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rhutchison/614a36e0a0f5411c95e43eb4d25364e0 to your computer and use it in GitHub Desktop.
Save rhutchison/614a36e0a0f5411c95e43eb4d25364e0 to your computer and use it in GitHub Desktop.
import {
Directive,
InjectFlags,
Input,
OnInit,
ɵɵdirectiveInject as inject,
} from '@angular/core';
import { ControlContainer } from '@angular/forms';
import { FormArray, FormBuilder, FormGroup } from '@ngneat/reactive-forms';
@Directive()
export abstract class FormArrayComponent<T extends object = any>
implements OnInit {
protected readonly _fb: FormBuilder;
protected readonly _parent?: ControlContainer;
@Input('formArray')
form: FormArray<T>;
@Input()
formArrayName: string;
constructor() {
this._fb = inject(FormBuilder);
this._parent = inject(
ControlContainer,
InjectFlags.Host | InjectFlags.Optional | InjectFlags.SkipSelf
);
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit() {
this._initForm();
}
// getFormArray<K extends keyof T>(prop: K): FormArray<T[K]> {
// return this.form.get(prop as string) as any;
// }
// getFormGroup<K extends keyof T>(prop: K): FormGroup<T[K]> {
// return this.form.get(prop as string) as any;
// }
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
private _initForm() {
if (this.form) return;
this.form = this.createForm();
const parentForm = this._parent?.control;
if (parentForm instanceof FormGroup && this.formArrayName) {
if (parentForm.contains(this.formArrayName)) {
this.form = parentForm.get(this.formArrayName) as FormArray<T>;
} else {
parentForm.addControl(this.formArrayName, this.form);
}
}
}
protected createForm() {
return this._fb.array<T>([]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment