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

问题描述 投票:0回答:1

我看了一下 这个 但它不工作 -- 可能是因为我的目标元素是在一个自定义组件中动态生成的 (<c-tabs>).

我还看了一下 这个 但我想这是行不通的,因为我无法触及自定义组件的代码。

相关元素enter image description here

超文本标记语言

<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控制台窗口中就可以工作。 也就是说,querySelected items得到id属性。

方法2.使用Angular的Renderer。使用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');
      }
    ...
}
javascript angular attributes add angular-renderer2
1个回答
1
投票

我不确定你想针对的是什么元素,如果你想通过类或标签来针对元素,但我认为下面的代码会帮助你。

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

© www.soinside.com 2019 - 2024. All rights reserved.