【问题标题】:Angular 8/9 How do I get the innerHTML of multiple elements with the same class name?Angular 8/9 如何获取具有相同类名的多个元素的 innerHTML?
【发布时间】:2023-11-24 01:25:01
【问题描述】:

我有一个 div,它将根据名为totalQuestionsList 的变量的长度创建我指定的次数。我想从每个 div 中的所有 <h5> 元素中选择 innerHTML

<div *ngFor="let item of totalQuestionsList; let i = index">
  <h5 class="question-num">Question #{{i+1}}</h5>
</div>

我该怎么做?任何帮助表示赞赏。

【问题讨论】:

  • “选择”是什么意思?你需要在组件上编辑它吗?或者以某种方式显示它?

标签: javascript html angular angular8 angular9


【解决方案1】:

您可以使用引用变量并使用 ViewChildren

<div *ngFor="let item of totalQuestionsList; let i = index">
  <h5 #h class="question-num">Question #{{i+1}}</h5>
</div>

@ViewChildren('h') elements:QueryList<ElementRef> 

你也可以在选择器类中使用指令

@Directive({
    selector:'.question-num'
})
export class QuestionDirective{
     constructor(public elementRef:ElementRef){}
}

并使用

 @ViewChildren(QuestionDirective) elements:QueryList<QuestionDirective> 
 //e.g. console.log(elements.first.elementRef)

【讨论】:

    【解决方案2】:

    在 ts 文件中。将 ElementRef 注入构造函数

    在那个类上有一个 nativeElement.innerHtml 属性

    使用它来获取您的内容

    【讨论】: