首页 > 解决方案 > Angular 8:如何在没有 html 标签的情况下使用 ngFor。我尝试了 ng-container 但它不起作用

问题描述

在我遇到很多问题后,我创建了以下想法来填补我的 Angular 项目中的空白问题。下面显示的对象来自 API,我想像下面提到的那样循环它。我无法使用ng-container标签,而不是span因为它会创建折旧的 html 标签问题。原因是,我在数组中提到的标签不会在同一个对象中关闭,它将被命名为字段的给定数组的下一个对象的下一个或下一个对象关闭。我的意思是,如果第0th 订单有值<p>my text并且第1st 订单将有值is this </p>

以下代码有效

            <div *ngIf="fill.type == 'lines'" >
              <span *ngFor="let f of fill.field">

                <span *ngIf="f.word_type == 'word'" [innerHTML]="makeSanitize(f.word)"></span>
                <span *ngIf="f.word_type == 'blank'"><input type="text" (keyup)="updateinput($event, f, miniq)" value="" [class.bg-success]="f.myanswer == f.word && miniq.answered && miniq.verified" [class.bg-danger]="f.myanswer != f.word && miniq.answered && miniq.verified" /></span>

              </span>
            </div>

但是下面的代码给出了一些错误

            <div *ngIf="fill.type == 'lines'" >
              <ng-container *ngFor="let f of fill.field">

                <ng-container *ngIf="f.word_type == 'word'" [innerHTML]="makeSanitize(f.word)"></ng-container>
                <ng-container *ngIf="f.word_type == 'blank'"><input type="text" (keyup)="updateinput($event, f, miniq)" value="" [class.bg-success]="f.myanswer == f.word && miniq.answered && miniq.verified" [class.bg-danger]="f.myanswer != f.word && miniq.answered && miniq.verified" /></ng-container>

              </ng-container>
            </div>

在此处输入图像描述

这个循环的 JSON 响应是

type: "lines",
field:

      0: {word: "<p>during table - "
          word_type: "word"
          myanswer: ""},
      1: {word: "apple"
          word_type: "blank"
          myanswer: ""},
      2: {word: " answer1</p>
          ↵
          ↵&lt;p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;- answer2</p>
          ↵
          ↵&lt;p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;- "
          word_type: "word"
          myanswer: ""},
      3: {word: "orange"
          word_type: "blank"
          myanswer: ""},
      4: {word: " answer3</p>
          ↵
          ↵&lt;p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;- test 
          answer4</p>"
          word_type: "word"
          myanswer: ""}

任何人都请帮助我如何在没有标签的情况下使用它或如何使其ng-container工作

标签: angulartypescriptng-container

解决方案


您不能绑定到,innerHTML因为它不是ng-container错误消息已经暗示的属性。改用数据绑定,这应该可以解决问题。( {{ makeSanitize(f.word) }} )

            <ng-container *ngIf="f.word_type == 'word'">{{ makeSanitize(f.word) }}</ng-container>
            <ng-container *ngIf="f.word_type == 'blank'">
                <input type="text" (keyup)="updateinput($event, f, miniq)" value="" [class.bg-success]="f.myanswer == f.word && miniq.answered && miniq.verified" [class.bg-danger]="f.myanswer != f.word && miniq.answered && miniq.verified" />
            </ng-container>

          </ng-container>

推荐阅读