K.Z
K.Z

Reputation: 5075

How to generate dynamic template.html based on receive API data

I am working on Angular questionnaire application part of which, I need to dynamically generate angular html template based on type and structure of question requested. for example I receive three questions where question 1 is radio button selector, question 2 is multiple selector and question three is free text, so in this instance component read three questions with 3 different type and is expected to generate template.html accordingly.

I need to know what is best way to approach this implementation.

one way I can think of dynamically generate html i.e. radio, multiple selector and free text

data is coming from Web API2/ .net core

Upvotes: 0

Views: 778

Answers (1)

Juan
Juan

Reputation: 2084

You can use the *ngFor and *ngIf directives to generate the template. With *ngIf you can show or hide the questions based on the question's type (selector, radio button...) and with *ngFor you can show the number of questions. Then use Angular interpolation {{}} to display info.

If this is your template:

<div *ngIf="radioButton" *ngFor="let r of radios">
    <radio-button>
        <option>{{ r.firstOption }}</option>
    </radio-button>
</div>

<div *ngIf="question" *ngFor="let q of questions">
    <div>{{ q.questionInfo }}</div>
</div>

In one instance you receive (from a service) a radio button option so you only display the first div as many times as radios length. Other instances would be diferent depending on the info retrieved by the service.

Upvotes: 1

Related Questions