In my small application, I have a feature where a question is displayed with certain words hidden and needs to be filled in by the user. The format of the question looks like this:
The {0} {1} {2} his {3} off
To achieve this functionality, I wrote the following code:
HTML section
<div *ngFor="let question of questionsArray">
---- some content here ----
<div [innerHTML]="createQuestion(question)"></div>
---- some content here ----
</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 have also included the DomSanitizer
in the constructor as shown below:
constructor(private sanitizer: DomSanitizer) {}
Although the inputs are being rendered correctly, I am facing an issue where I am unable to type anything in the input field. I suspect that the bypassSecurityHtml
method might not be working correctly without using a Pipe
as suggested here. Since the dynamic creation of inputs based on each question prevents me from using it within a pipe, I am seeking assistance on how to resolve this issue...
If anyone could provide some guidance, it would be greatly appreciated.