javascript - 如何在我的 Angular 组件中动态渲染带有样式和 *ngFor 的 HTML 选择框?

标签 javascript angular typescript

因此,我正在创建一个简单的填空应用程序,并且我想用选择框替换字符串中的标识符。

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/

相关文章:

javascript - 为 Charts.js 添加 for 循环/foreach 循环

javascript - 使用 Ajax 更新页面的一部分而不使用 jQuery

Angular 4 将服务响应值传递给多个组件

angular - 如何使用 Jasmine Marbles 为 angular 的 HttpClient 编写单元测试?

javascript - tslint.json 在 VS 代码中不起作用

javascript - 为什么这个函数返回未定义?

php - 当我不把它放在 jQuery(document).ready 中时,jquery 不工作

angular - fxLayoutWrap 不工作

javascript - Yeoman 在模板中循环

javascript - 如何从 Javascript 读取和写入 Angular 组件变量?