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

标签 javascript angular attributes addition angular-renderer2

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

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

相关元素 enter image description here

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 控制台窗口中起作用。也就是说,querySelected 项目获取 id 属性。

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

//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');
      }
    ...
}

最佳答案

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

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。

关于javascript - 如何向 Angular2+ 中动态创建的元素添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61897791/

相关文章:

javascript - jQuery、Prototype、Extjs、mootools、Scriptaculous、Spry、YUI、DOJO 框架之间有什么区别?

javascript while() 循环创建一行单元格而不是表格

javascript - 使用 angular.forEach() 中的键和值动态创建 Angular 对象

angular - 当 ngModel 在没有用户输入的情况下从组件更改时,ngModelChange 不会触发

javascript - 如何从独立的纯 JavaScript 函数调用 Angular 4 方法?

c# - 了解 C# 中的属性

powershell - 在 powershell 中检索 NUnit 自定义属性

javascript - 使用 javascript 更改 img src 时添加过渡

angular - Angular2 中的@Input() 不适用于字符串

python - matplotlib 属性错误问题