[英]How can I dynamically render HTML select box with styles and *ngFor in my angular component?
因此,我在blanks應用程序中創建了一個簡單的填充,並且在字符串中有標識符,我想用選擇框替換它。
打字稿
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列表。
任何幫助將不勝感激。
按照我之前的答案(&刪除),您提出了動態渲染的示例。
根據您提供的內容,我進行了一次堆疊閃電戰:
https://stackblitz.com/edit/my-angular-starter-xelsuj?file=app/app.component.ts
在這次堆疊閃電戰中,您將看到內容是動態的,但仍在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],
}));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.