I have a small app in which I receive a question with some hidden words to be written down like this:
The {0} {1} {2} his {3} off
When this string is received, each {x}
string has to be substituted with an input that the user will fill with the correct answer. So for that, I created this code:
HTML part
<div *ngFor="let question of questionsArray">
---- some stuff ----
<div [innerHTML]="createQuestion(question)"></div>
---- some stuff ----
</div>
Typescript function:
createQuestion(question: string): SafeHtml {
let innerHtml = '';
let words = question.split(' ');
for (let index = 0; index < words.length; index++) {
const element = words[index];
if (element.indexOf('{') >= 0) {
innerHtml += '<input type="text" name="test"></input>';
} else {
innerHtml += element;
}
}
return this.sanitizer.bypassSecurityTrustHtml(innerHtml);
}
I also added the DomSanitizer
in the constructor like this:
constructor(private sanitizer: DomSanitizer) {}
It works fine and draws inputs like this:
But I can't write anything on the input. I guess that maybe the byPassSecurityHtml
might not be working because I didn't use any Pipe
as suggested here. But, as I need it to be created in a dynamic way as it needs to be called foreach question in my DOM, I can't figure out how to use it correctly...
Can anybody give me a hand with this?