Search code examples
angularangular2-formsangular2-components

Getting selector name from json in Angular 2


I want a dynamic form. In which element details will come from json.

I have a json like this :

{
"FormElements": [
    {
        "selectorName": "text-input",
        "id": "",
        "class": "location",
        "name": "simpletext",
        "placeholder": "Enter your text here",
        "label": ""
    },
    {
        "selectorName": "radio-button",
        "id": "radio",
        "class": "",
        "name": "radio-name",
        "placeholder": "",
        "label": "Push this"
    }]
}

and My component template is something like:

<form>
    <div *ngFor="let fe of data.FormElements">
        <{{fe.selectorName}} idName="{{fe.id}}" className="{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.labell}}"></{{fe.selectorName}}>
    </div>
</form>

But this is giving an error :

Unexpected closing tag "{{fe.elementName}}" ("{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.labell}}">[ERROR ->]</{{fe.elementName}}>

Please Help. Thanks!


Solution

  • You can't just use dynamic values for tag names like that, what I suggest you do is use ngSwitch like this

    <form>
        <div *ngFor="let fe of data.FormElements">
            <div [ngSwitch]="fe.selectorName">
                <div *ngSwitchCase="'text-input'">
                    <text-input idName="{{fe.id}}" className="{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.label}}"></text-input>
                </div>
    
                <div *ngSwitchCase="'radio-button'">
                    <radio-button idName="{{fe.id}}" className="{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.label}}"></radio-button>  
                </div>
            </div>
        </div>
    </form>