要获取其他元素放置在其上的元素的ID,可以使用Angular的ViewChild装饰器来获取对应的元素引用。以下是一个示例解决方案:
HTML模板:
Element 1
Element 2
组件类:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: '...',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements AfterViewInit {
@ViewChild('element1') element1: ElementRef;
@ViewChild('element2') element2: ElementRef;
ngAfterViewInit() {
const element1Id = this.element1.nativeElement.id;
const element2Id = this.element2.nativeElement.id;
console.log('Element 1 ID:', element1Id);
console.log('Element 2 ID:', element2Id);
}
}
在这个示例中,我们使用了ViewChild装饰器来获取两个元素的引用,然后通过nativeElement属性来获取它们的ID。在ngAfterViewInit生命周期钩子中,我们可以访问这些元素的ID并将其打印到控制台上。
请注意,为了能够访问nativeElement属性,我们需要引入ElementRef类并将其注入到组件类中。