繁体   English   中英

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

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

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

我也看过这个,但我认为这不起作用,因为我无法触摸自定义组件的代码。

相关要素在此处输入图像描述

HTML

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

我尝试了以下方法来定位它。 没有工作。

方法 1. 使用普通的旧 Javascript:

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

我试图在 ngOnInit 和 ngOnViewInit 方法中使用上述内容,但这没有帮助。 奇怪的是,这种方法在页面呈现后在 Chrome 控制台 window 中有效。 即querySelected 项获取id 属性。

方法2。 使用 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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM