【发布时间】:2020-10-08 15:50:09
【问题描述】:
我想在一个角度组件中使用类型脚本函数显示格式化的 HTML,我希望它显示来自不同类型的问题,我试过这个,
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>
但是 HTML 只显示为纯文本,在页面上写满了代码,你知道如何解决这个问题吗?
编辑:编辑的代码更符合上下文,问题来自 json 文件,其中有 3 种类型,我创建了一个函数将它们转换为 Question 并根据类型我想要 3 种显示方式它们以 3 种不同的形式呈现,每种类型都作为一个长的 HTML 开发,并以不同的标签和元素显示
【问题讨论】:
-
在这里这样做有什么意义?要注入 html,你需要使用 [innerHtml]
-
您可以找到几种解决方案:ng-template 是一个用于渲染 HTML 模板的 Angular 元素,Renderer2 类允许您操作/创建 DOM 元素
-
有没有更好的方法从对象列表生成 HTML?
标签: html angular typescript angular-cli