我看过this但它不起作用——可能是因为我定位的元素是在自定义组件 ( <c-tabs>
) 内动态生成的。
我也看过this但我认为这是行不通的,因为我无法触及自定义组件的代码。
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/