vendredi 27 juillet 2018

How to implement polymorphism in Angular in running time?

Component inheritance is quite straight forward in Angular >2, just a matter of extending the parent class:

import { ParentComponent } from './parent.component';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent extends ParentComponent {
}

This works pretty well for a lot of use cases.

Now, let's imagine that I have a parent class Person, and two children classes, Employee and Contractor. I don't know if a person is a contractor or an employee until I query the database.

So my question is, what is the best way to subclass Person based on a flag that is received at running time? Is there a design pattern that fits this use case?

Aucun commentaire:

Enregistrer un commentaire