首页 文章

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

提问于
浏览
0

假设我有以下角度模板:

<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> ,但我面临的问题是图标仅出现在某些情况下,因此,我无法通过使用 ElementRefchildren 属性为 <b> 添加样式,因为 Renderer2 正在投掷错误说明无法找到 style 属性 .

请帮我解决这个问题 .

1 回答

  • 1

    只需使用 [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>
    

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

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

    这是用于在ViewInit之后更新上下文变量的值 . 现在跟随课程的变化:

    @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

相关问题