因此,我正在创建一个简单的填空应用程序,并且我想用选择框替换字符串中的标识符。
typescript
const string = `##blank.0## is the capital city of China. It's most famous attraction is## blank .1##.`;
ngOnInit() {
this.answers.forEach(a => {
this.string = this.sanitizer.bypassSecurityTrustHtml(this.string.replace(`##blank.${a.index}##`,
`<select class="select-boxes">
<option *ngFor="let answer of ${a.answers}" [value]="answer.id">
{{ answer.content }}
</option>
</select> `));
});
}
HTML
<p [innerHTML]="string"></p>
问题
它渲染选择框,但不渲染样式或 *ngFor 列表。
任何帮助将不胜感激。
最佳答案
按照我之前(和删除的)答案,您重新请求了动态渲染的示例。
我已经根据您提供的信息进行了堆栈 Blitz :
https://stackblitz.com/edit/my-angular-starter-xelsuj?file=app/app.component.ts
在此 stackblitz 中,您将看到内容是动态的,但仍在 Angular 上下文中。因此,您仍然可以使用 Angular 指令,并且不再依赖 innerHTML
。
export class AppComponent {
content: SafeHtml;
str = `##blank.0## is the capital city of China, ##blank.1## is the capital of France.`;
answers = [{
ref: 0,
answers: [
{ id: 0, content: 'Beijing' },
{ id: 1, content: 'Shanghai' },
{ id: 2, content: 'Ghuangzhou' },
{ id: 3, content: 'The Great wall' },
],
bit: undefined,
}, {
ref: 1,
answers: [
{ id: 0, content: 'Stockholm' },
{ id: 1, content: 'New York' },
{ id: 2, content: 'Malibu' },
{ id: 3, content: 'Paris' },
],
bit: undefined,
}];
constructor(sanitizer: DomSanitizer) {
// Split the string into bits
let bits = this.str.split(/##blank\.\d+##/);
// remove empty bits (mostly start & end)
bits = bits.filter(bit => !!bit);
// Add the bit to the answer
this.answers = this.answers.map((answer, index) => ({
...answer,
bit: bits[index],
}));
}
}
关于javascript - 如何在我的 Angular 组件中动态渲染带有样式和 *ngFor 的 HTML 选择框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431228/