【发布时间】:2017-02-28 13:51:37
【问题描述】:
我正在尝试根据数组中元素的数量动态设置 div 的 left。为此,我在[ngStyle] 中使用calc() 方法,其中data.questions 是我从中绘制的对象数组。
为了证明计算有效,我将其添加到<p> 以进行调试。
我的 html 中有以下内容:
<div id="progress">
<div *ngFor="let question of data.questions; let i = index;"
[ngStyle]="{'left': 'calc('+(i / data.questions.length * 100) + (1 / (data.questions.length * 2) * 100)+'%)'}">
<p>{{(i / data.questions.length * 100) + (1 / (data.questions.length * 2) * 100)}}%</p>
</div>
</div>
下面是渲染的内容。您可以看到[ngStyle] 仅适用于生成的 3 个 div 中的第一个。为什么会这样?
<div _ngcontent-ydx-7="" id="progress" ng-reflect-ng-style="[object Object]" style="border-color: rgb(127, 167, 187);">
<div _ngcontent-ydx-7="" ng-reflect-ng-style="[object Object]" style="left: calc(16.6667%);">
<p _ngcontent-ydx-7="">16.666666666666664%</p>
</div>
<div _ngcontent-ydx-7="" ng-reflect-ng-style="[object Object]">
<p _ngcontent-ydx-7="">49.99999999999999%</p>
</div>
<div _ngcontent-ydx-7="" ng-reflect-ng-style="[object Object]">
<p _ngcontent-ydx-7="">83.33333333333331%</p>
</div>
</div>
注意: 我花了相当长的时间试图为此做一个 plunkr,但是它一直给我在我的 ngFor 中使用 data.questions 的错误,即使这确实如上面所证明的那样有效(我的 plunkr 技能还在开发中……).
下面是data.questions的简化版供大家一起玩...
private questionOptions: string[] = [
`Strongly Agree`,
`Agree`,
`Slightly Agree`,
`Slightly Disagree`,
`Disagree`,
`Strongly Disagree`
];
private data = {
questions: [{
text: `Great service makes a difference to the customer.`,
options: [{
text: this.questionOptions[0],
score: 3
},
{
text: this.questionOptions[1],
score: 2
},
{
text: this.questionOptions[2],
score: 1
},
{
text: this.questionOptions[3],
score: -1
},
{
text: this.questionOptions[4],
score: -2
},
{
text: this.questionOptions[5],
score: -3
}
]
},
{
text: `Great service can be provided every time we interact with our customers. `,
options: [{
text: this.questionOptions[0],
score: 3
},
{
text: this.questionOptions[1],
score: 2
},
{
text: this.questionOptions[2],
score: 1
},
{
text: this.questionOptions[3],
score: -1
},
{
text: this.questionOptions[4],
score: -2
},
{
text: this.questionOptions[5],
score: -3
}
]
},
{
text: `Customer facing staff have more impact on providing great service than I do.`,
options: [{
text: this.questionOptions[0],
score: -3
},
{
text: this.questionOptions[1],
score: -2
},
{
text: this.questionOptions[2],
score: -1
},
{
text: this.questionOptions[3],
score: 1
},
{
text: this.questionOptions[4],
score: 2
},
{
text: this.questionOptions[5],
score: 3
}
]
}
]
};
【问题讨论】:
-
为什么你的css属性值被
's包裹了? -
[style.left]="calc("+(i / data.questions.length * 100) + (1 / (data.questions.length * 2) * 100)"+"% )"
-
这里不需要使用
calc()。 -
@RobbyCornelissen 抱歉 - 为了简化问题,我去掉了等式的所有其他部分。它们相当冗长,并且要离开它们,直到我注意到它不适用于仅百分比。
-
@echonax 我不必这样做,所以它不会尝试将
calc()转换为打字稿函数,而是将其作为字符串值传递?
标签: html css angular typescript