So in my Angular project, I was trying to have an abstract base class for editing forms. Let's call it Editor
.
There will be many components that do operations on a form so they inherit from the base class. For example, there is a component which edits a user. So the component would look like this
export abstract class Editor {
public form!: FormGroup;
private _hasChanges = false;
constructor() {
this.createForm();
this.subscribe();
}
protected abstract createForm(): void;
private subscribe(): void {
this.form.valueChanges.subscribe((_) => {
this._hasChanges = true;
});
}
public get hasChanges(): boolean {
return this._hasChanges;
}
}
@Component({
selector: 'user-editor',
templateUrl: './user-editor.component.html',
styleUrls: ['./user-editor.component.scss'],
})
export class UserEditorComponent extends Editor {
public dummy = 'dummyText';
constructor(private fb: FormBuilder) {
super();
}
protected createForm(): void {
this.form = this.fb.group(
name: ['', Validators.required]
);
}
}
But this sample won't work! in the implementatoin of createForm
, this.fb
will be undefined. Even more, when putting a breakpoint and inspecting this
. It seems like we are not in the chlid component but in the parent component.
Since the 'dummy' variable is not there.
I made a minimal reproducible sample here