Here is an example of element class
export class Element {
fields = []
}
And here are two field classes
export class SmallText {
value
constructor(value) {
this.value = value
}
}
export class LargeText {
value
constructor(value) {
this.value = value
}
}
Imagine we have an instance of this element
export class Element {
fields = []
constructor(){
this.fields.push(new SmallText("foo"))
this.fields.push(new LargeText("bar"))
}
}
Each field has a unique template, for example
<!-- the small text is displayed as an input -->
<input>
<!-- while the large text appears as a textarea -->
<textarea></textarea>
Now, I want to iterate through the fields array and display the corresponding template for each field.
The current solution involves using ngFor directive like so:
<field *ngFor="let field of element.fields" [inputField]="field"></field>
Within the field component, there exists logic such as:
<input *ngIf="inputField.constructor.name == 'SmallText'">
<textarea *ngIf="inputField.constructor.name == 'LargeText'"></textarea>
This approach becomes troublesome in production as class names get overwritten, necessitating the maintenance of a mapping in a service.
I propose having separate components for SmallText and LargeText so that when looping through the element.fields array, each component is instantiated with its respective template. This way, we avoid the need for additional logic to handle different field types.
Is there a more efficient solution to this issue?