Created
May 25, 2021 13:46
-
-
Save rhutchison/614a36e0a0f5411c95e43eb4d25364e0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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