6

I'd like to display formated HTML using type script function in an angular component, I wanted it to display question from diferent type, I tried this,

import {Component, OnInit} from '@angular/core';
import {TP, Question, Qtype} from "../tp";
import * as Exercice from '../assets/Exercice.json';

@Component({
  selector: 'app-tp',
  templateUrl: './tp.component.html',
  styleUrls: ['./tp.component.css']
})
export class TpComponent implements OnInit {


  constructor() {
  }

  ngOnInit(): void {
  }

  displayQCM(question: Question) {
    return `
      <div>
            <hr class="w-100">
            <h3>Question n°${question.number} ${question.questionType}</h3>
            <p>${question.questionContent}</p>
            ...
            QCM question element
            ...
        </div>
    `;
  }

  displayTrueOrFalse(question: Question) {
    return `
      <div>
            <hr class="w-100">
            <h3>Question n°${question.number} ${question.questionType}</h3>
            <p>${question.questionContent}</p>
            ...
            true or false question element
            ...
        </div>
    `;
  }

  displayQuestion(question: Question) {
    return `
      <div>
            <hr class="w-100">
            <h3>Question n°${question.number} ${question.questionType}</p>
            <p>${question.questionContent}</p>
            ...
            normal question element
            ...
        </div>
    `;
  }
}
<div class="row justify-content-center">
  <div class="col-12 col-lg-6">
    <h2>Questions</h2>
    {{displayQCM()}}
    {{displayQuestion()}}
    {{displayTrueOrFalse()}}
  </div>
</div>

but the HTML display only as plain text writing fully the code on the page, do you know how to fix this ?

EDIT: edited code to be more in the context, the question comes from a json file and there's 3 type of them, I created a function to translate them into Question and depending on there type I want 3 way to display them in 3 different forms, each type as a long HTML development and are displayed with different tag and element

3
  • Whats the point of doing that here? to inject html, you need to use [innerHtml] Commented Jun 18, 2020 at 14:45
  • 1
    You can find out about several solutions: ng-template is an Angular element used to render HTML templates, The Renderer2 class that allows you to manipulate/create DOM elements Commented Jun 18, 2020 at 14:47
  • is there a better way to generate HTML from a list of object ? Commented Jun 18, 2020 at 14:47

4 Answers 4

11

You need to use [innerHTML] property in your html file

<div class="row justify-content-center">
  <div class="col-12 col-lg-6">
    <h2>Questions</h2>
   <div [innerHTML]="displayQCM()"></div> 
    <div [innerHTML]="displayQuestion()"></div>
    <div [innerHTML]="displayTrueOrFalse()"></div>
  </div>
</div>

Output

Sign up to request clarification or add additional context in comments.

Comments

1

If you are just trying to inject dynamic content you need to sanitize your html string and then use innerHtml. From your question Im not sure what the goal is and there must be a better way without injecting Html but you would need to clarify the goal.

questions: Array<SafeHtml> = new Array<SafeHtml>();
myJson: Array<string> = []; //I dont know where its coming from

  constructor(private sanitizer: DomSanitizer) {
  }

  ngOnInit(): void {
      myJson.forEach((question) => { 
          this.questions.push(this.sanitizer.sanitize(question)); 
      })
  }

  <div class="row justify-content-center">
    <div class="col-12 col-lg-6">
      <h2>Questions</h2>
      <div *ngFor="let q of questions" [innerHtml]="q"></div>
    </div>
  </div>

4 Comments

how can I do if I don't know the amout of question there will be ?
Well you can build an array of sanitized html. But where are the questions coming from?
from a json file
@lolozemadnessgamer edited, I think something along those lines would work but that is if there is no other way to hardcode the question in your template and display/hide them dynamically. The other thing is I made up that the json is an Array<string> which might be false in your case.
1

Why you don't use ngFor to list all questions?

HTML

<div class="row justify-content-center">
      <div class="col-12 col-lg-6">
        <h2>Questions</h2>
             <div *ngFor="let question of allQuestions">
                <hr class="w-100">
                <h3>Question n°{{question.number}} {{question.questionType}}</h3>
                <p>{{question.questionContent}}</p>
            </div>
      </div>
    </div>

And allQuestions is your question array

You can add conditions depends on question type with *ngIf:

 <p *ngIf="question.questionType=== 'normal'"></p>

or you can use ng-template:

<ng-template [ngIf]="question.questionType === 'normal'">Your HTML code for normal question</ng-template>
<ng-template [ngIf]="question.questionType === 'trueFalse'">Your HTML code for trueFalse question</ng-template>

Comments

0

Exemple TS :

displayQCM : boolean;
displayQuestion : boolean;
displayTrueOrFalse : boolean;

HTML

<div class="row justify-content-center">
<div class="col-12 col-lg-6">
<h2>Questions</h2>
<div *ngIf="displayQCM">...</div>
<div *ngIf="displayQuestion">...</div>
<div *ngIf="displayTrueOrFalse">...</div>
</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.