You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Angular中mat-card组件的坐标与尺寸?

获取Angular中mat-card组件的坐标与尺寸

你可以通过nativeElement结合浏览器原生API getBoundingClientRect()直接获取mat-card的坐标与尺寸,这是最直接有效的方案,具体实现如下:

核心方法:getBoundingClientRect()

调用该方法会返回一个DOMRect对象,包含元素的视口坐标(left、top、right、bottom)和尺寸(width、height),完全满足坐标与尺寸的获取需求。

修改代码实现

在你的AppComponent的newCardClick方法中,遍历已有卡片列表,对每个卡片的nativeElement调用该方法即可:

newCardClick() {
  // 获取所有已有卡片的坐标与尺寸
  this.cards.forEach(card => {
    const rect = card.element.nativeElement.getBoundingClientRect();
    console.log(`卡片ID: ${card.id}`);
    console.log(`视口坐标:左 ${Math.round(rect.left)}px,上 ${Math.round(rect.top)}px`);
    console.log(`尺寸:宽 ${Math.round(rect.width)}px,高 ${Math.round(rect.height)}px`);
  });

  this.cards.push(new Card(
    this.id, "Test"+this.id, "", (new Date()).toString(), { x: 10, y: 10+this.id++*85}
  ));
}

额外说明

  1. 坐标基准转换:left/top是元素相对于浏览器视口左上角的坐标,若需获取相对于父容器(如.main__div)的坐标,可减去父元素getBoundingClientRect()返回值的left和top。
  2. 拖拽后实时获取:因为你使用了cdkDrag,可通过cdkDragEnded事件触发获取拖拽后的最新坐标,在Card组件中添加如下代码即可:
<mat-card #cardElement class="card" 
  [cdkDragFreeDragPosition]="card.position"
  cdkDrag
  (cdkDragEnded)="onDragEnd()">
    <mat-card-title>{{card.header}}</mat-card-title>
    <mat-card-subtitle>{{card.description}}</mat-card-subtitle>
</mat-card>
// CardComponent中添加方法
onDragEnd() {
  const rect = this.element.nativeElement.getBoundingClientRect();
  console.log(`卡片${this.card.id}拖拽后坐标:左 ${rect.left}px,上 ${rect.top}px`);
}
  1. 调用时机:确保在组件AfterViewInit生命周期之后调用该方法,此时DOM已完全渲染,nativeElement能正确获取元素实例。你的代码中已在CardComponent的ngAfterViewInit中完成card.element的赋值,符合要求。

内容的提问来源于stack exchange,提问作者Evgeny Cheryomushkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:30:34