我'm here today because I'想知道NG Style with Angular( my version being the 6 ) . 当 I use a function 返回一个值时,我怎么能 update [ngStyle] .
As always, here is a simplified example of my problem:
我从一个对象数组生成div . 对于每个部分, there are two div :左侧一个,右侧一个 .
The size of the left div changes depending on the content ,所以它可以同时做50px和125px .
I want the right div to fit the size of the one on his left ,总是那个大小的一半(在getLeftDivHeight中为2) . 显然,这将在每个部分(容器)中完成 .
How can I make the ngStyle update when the div's height to the left changes (由于调整大小,添加内容或页面显示时间)? )
这是代码:
HTML
<section class = "Container" *ngFor="let oneContent of allContent">
<div id = "{{oneContent.id}}" style="float: left">
<p> {{oneContent.Content}} </ p>
</div>
<div style="float: right" [ngStyle]="height: getLeftDivHeight(oneContent.id, 2)">
</div>
</div>
Typescript (只有相关功能)
getLeftDivHeight(id: string, divisionNumber: number): string {
height = document.GetElementById(id).getBoundingClientRect().height /
divisionNumber;
return height + 'px';
}
请注意,我不是在寻找HTML解决方案,而是一个Angular解决方案,上面的代码只是解释我的问题的一个例子 .
Thank you in advance
2 回答
您可以从getLeftDivHeight方法返回整个样式字符串,例如
height: 100px
getLeftDivHeight(id: string, divisionNumber: number): string { height = document.GetElementById(id).getBoundingClientRect().height / divisionNumber; return
height: $px; }
或者您可以在模板中使用以下语法
[style.height.px]="getLeftDivHeight(parameters)"
仅返回方法中的数字高度值 .所以,我终于设法使用指令 .
我使用ElementRef来访问我的右边div的HTML对象 .
然后,我使用Dom访问左div高度
然后我使用
this.renderer.setElementStyle()
来应用样式我还了解到使用offscrollheight进行数学计算并不是一个好主意!