如何在 Angular2+ 中向动态创建的元素添加属性?

How do I add an attribute to a dynamically created element in Angular2+?

我看过 ,但它不起作用 -- 可能是因为我定位的元素是在自定义组件 (<c-tabs>) 中动态生成的。

我也看过 但我认为这行不通,因为我无法触及自定义组件的代码。

相关要素

HTML

<c-tabs #mainComponentTabs1 [items]="tabItems"></c-tabs>

我尝试了以下方法来定位它。 None 有效。

方法 1. 使用普通旧 Javascript:

ngAfterViewInit() {
    let att = document.createAttribute("id");
    att.value = "yada1";
    document.querySelectorAll(".c-tabs .hydrated")[0].setAttributeNode(att);
}

我曾尝试在 ngOnInit 和 ngOnViewInit 方法中使用上述内容,但这没有帮助。 奇怪的是,此方法在页面呈现后在 Chrome 控制台 window 中起作用。 也就是说,querySelected items 获取 id 属性。

方法二。使用 Angular 的 Renderer2。 (诚​​然,我不知道如何获取需要 id 的特定原生元素。

//first, declare target custom component element with viewchild:
export class MainComponent implements OnInit, AfterViewChecked, AfterViewInit {
    @ViewChild('mainComponentTabs1', { static: true }) c_tabs1: ElementRef;
    ...
    ngAfterViewChecked() {
        //neither of these approaches works.
        const c_tabs1El = this.c_tabs1.nativeElement;    
        this.renderer.setAttribute(c_tabs1El.items[0], 'id', 'dashboard-tab-link-search');

        const c_tabs1El2 = document.querySelectorAll("button.c-item");
        this.renderer.setAttribute(c_tabs1El2[0].nativeElement, 'id', 'dashboard-tab-link-dashboard');
      }
    ...
}

如果您尝试通过 class 或标记来定位元素,我不确定您要定位哪些元素,但我认为以下代码会对您有所帮助:

export class MainComponent implements OnInit, AfterViewChecked, AfterViewInit {
    // the static property must be true only if you are using it in ngOnInit
    @ViewChild('mainComponentTabs1', { static: false }) c_tabs1: ElementRef;
    ...
    ngAfterViewInit() {
        const targetElements = this.c_tabs1.nativeElement.querySelectorAll('button.c-item')

        targetELements.forEach((el, index) => this.renderer.setAttribute(el, 'id', `dashboard-tab-link-search-${index}`));
      }
    ...
}

不要直接触摸DOM。