gpt4 book ai didi

javascript - Angular 模板引用 : Bind height of one div to height of another

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:29 25 4
gpt4 key购买 nike

我想将一个 Angular 组件的高度绑定(bind)到一个 div 的高度。我正在尝试使用模板引用来获取高度。

是否有可能以一种干净的方式使用这种方法来做到这一点?我想在下面的代码片段中这样做。

<div [style.height.px]="section1.offsetHeight"></div>
<app-custom-tag #section1>
</app-custom-tag>

我想要 <div> 的高度等于 <app-custom-tag> 的高度

我不能为此使用 css 列布局,因为这两个元素没有放在一起。

最佳答案

我认为您还需要做一些额外的事情。

当您在 View 中引用一个组件时,您将获得类实例。考虑到这一点,您可以注入(inject) ElementRef,以便获取有关native 元素 的信息。

考虑这个例子:

foo.component.ts

@Component({
selector: 'foo',
template: `foo`,
styles: [`:host { color: red; display: block; height: 300px; } `]
})
export class FooComp {

get offsetHeight () {
return this.el.nativeElement.offsetHeight;
}

constructor (private el: ElementRef) { }
}

应用程序组件.ts

@Component({
selector: 'my-app',
template: `
<foo #f></foo>
{{ f.offsetHeight }}

<br>

<div style="border: 1px solid black" [style.height.px]="f.offsetHeight"></div>
<!-- <div style="border: 1px solid black" [ngStyle]="{ height: f.offsetHeight + 'px' }"></div> -->

<br>

<input #i id="demo" type="text">

{{ i.id }}
`,
})
export class AppComponent { }

当您在 View 中引用 DOM 元素时,您将获得该 DOM 元素。

ng-run demo .

关于javascript - Angular 模板引用 : Bind height of one div to height of another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com