角度组件在视图初始化后获取组件的宽度高度

时间:2019-11-28 13:44:30

标签: css angular

我试图在AfterViewInit之后获取组件的宽度和高度。这些值用于在SVG画布上绘制。

TS:

  @ViewChild("svg", { static: true }) svgEleRef;

  ngAfterViewInit(): void {
    this.initCanvas();
  }

  initCanvas() {
    this.svg = d3.select(this.svgEleRef.nativeElement); // correct svg

    console.log(this.svgEleRef.nativeElement); // print value
    console.log(this.svgEleRef.nativeElement.clientWidth); // print 0
  }

CSS:

svg {
  width: 100%;
  height: 100%;
  background: aqua;
}

this.svgEleRef.nativeElement在Chrome控制台中显示clientWidth和clientHeight:

svg
assignedSlot: null
attributes: NamedNodeMap {0: _ngcontent-sab-c3, _ngcontent-sab-c3: _ngcontent-sab-c3, length: 1}
baseURI: "http://localhost:4200/"
clientHeight: 754
clientLeft: 0
clientTop: 0
clientWidth: 678

但是this.svgEleRef.nativeElement.clientWidth会打印0

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试这样:

@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html',
  styleUrls: ['./component-name.component.css'],
  host: {
    '(window:resize)': 'getWidthAndHeight($event)'
  }
})
export class CoomponentNameComponent implements OnInit {

  constructor() { }

  ngOnInit(){}

  ngAfterViewInit() {
    this.getWidthAndHeight()
  }

  getWidthAndHeight(evt?) {
    var screenHeight : number = window.innerHeight;
    var screenWidth : number = window.innerWidth;
  }

}

答案 1 :(得分:0)

除了高度百分比,您正在做所有正确的事情。您应该用CSS的pxvh单位替换高度。

DEMO

HTML

<div class="svg" #svg></div>

CSS

.svg {
  width: 100%;
  height: 100vh;
  background: aqua;
}

控制台输出

enter image description here

我希望这会有所帮助。

谢谢。