如何将使用 Renderer2 的样式应用到 ElementRef 的子节点 -> Angular 中的 nativeElement

How to Apply styled using Renderer2 to a child node of ElementRef -> nativeElement in Angular

假设我有以下 Angular 模板:

<p class="margin0 text-overflow table-cell" #ParentP>
  <span id="managerDisplayName" #FirstSpan class="bold" title="{{ someBinding 1}}">{{ someBinding2 }}</span>
  <span id="regionName" #SecondSpan class="bold regionName" title="{{ someBinding3 }}"> {{ someBinding4 }}</span> 
  <span class="service-level-icon">
    <b placement="bottom" #IconHolder triggers="mouseenter:mouseleave" container="body" *ngIf=" someCondition1 " popoverTitle="" [ngbPopover]="servicelevelcontent"><i class="somecon"></i></b>                                        
  </span>
</p>

这段代码使用 *ngFor 生成了多次。

我想通过计算第一个和第二个 <span> 的宽度来动态更改 <b> 标签的左对齐。

我已经尝试使用 [style.left.px]="FirstSpan.offsetWidth + SecondSpan.offsetWidth + 3",但这会引发 Expression Changed after Checked 错误。

然后我想尝试使用 QueryList<ElementRef> 但我面临的问题是该图标仅在某些情况下存在,因此我无法为 [=13= 添加样式] 通过使用 ElementRefchildren 属性 作为 Renderer2 抛出错误说明无法找到 style 属性.

请帮我解决这个问题。

只需使用 [style.left.px] 并使用 @viewChildren 来选择这些元素。将您的视图代码更新为:

<p class="margin0 text-overflow table-cell" #ParentP>
  <span id="managerDisplayName" #FirstSpan class="bold" title="{{ someBinding 1}}">{{ someBinding2 }}</span>
  <span id="regionName" #SecondSpan class="bold regionName" title="{{ someBinding3 }}"> {{ someBinding4 }}</span> 
  <span class="service-level-icon">
    <b placement="bottom" #IconHolder [style.left.px]="updatedLeftStyle" triggers="mouseenter:mouseleave" container="body" *ngIf=" someCondition1 " popoverTitle="" [ngbPopover]="servicelevelcontent"><i class="somecon"></i></b>                                        
  </span>
</p>

然后在组件 class 代码中确保导入 ChangeDetectorRef :

import { ChangeDetectorRef } from '@angular/core';

这是为了在 ViewInit 之后更新上下文变量的值。现在跟随 class 的变化:

@ViewChildren('FirstSpan,SecondSpan') spans:QueryList<ElementRef>;

constructor(private cdRef:ChangeDetectorRef) { }

ngAfterViewInit() {
    console.debug(this.spans); 
    let eleArr: any = this.spans.toArray();
    this.updatedLeftStyle = eleArr[0].nativeElement.offsetWidth + eleArr[1].nativeElement.offsetWidth;
    this.cdRef.detectChanges();
  }

Demo Example