要根据另一个HTML元素的位置设置ngStyle的margin,可以使用Angular的ViewChild和ElementRef来获取对应元素的位置信息,然后根据这些信息来设置ngStyle的margin。
下面是一个示例代码:
在 HTML 文件中:
Element 1
Element 2
在 TypeScript 文件中:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
@ViewChild('element1', {static: true}) element1: ElementRef;
@ViewChild('element2', {static: true}) element2: ElementRef;
setMargin(element1: ElementRef, element2: ElementRef): any {
const rect1 = element1.nativeElement.getBoundingClientRect();
const rect2 = element2.nativeElement.getBoundingClientRect();
const marginTop = rect2.top - rect1.top;
const marginLeft = rect2.left - rect1.left;
return {
'margin-top': `${marginTop}px`,
'margin-left': `${marginLeft}px`
};
}
}
在上述代码中,我们使用ViewChild来获取对应的HTML元素的引用,然后使用ElementRef的nativeElement属性来获取元素的位置信息(通过getBoundingClientRect方法)。最后,我们根据这些位置信息计算出margin的值,并返回一个包含margin样式的对象,通过ngStyle绑定到element2上。