【问题标题】:CSS not working as desired with interpolation in angularCSS无法按角度插值工作
【发布时间】:2018-05-30 20:29:21
【问题描述】:

我有一个用例,我想在我的网络应用程序中为用户显示通知。要显示的通知数量将取决于用户已获得多少查询。因此,我尝试使用插值来动态显示某个用户有多少通知。我的问题是,我的 CSS 样式只有在提供的通知数量是静态的情况下才有效。

这是使用静态数字时的示例(这是我想要的结果):image of how i want my notifications to look like

这是通过以下代码实现的:

 <li class="nav-item dropdown" dropdown>

  <span class="notification has-badge" innerHTML="4" 
   *ngIf="newNotificationsAvailable" >  </span>

       <a dropdownToggle mdbWavesEffect type="button" class="nav-link 
        dropdown-toggle waves-light fa fa-user" *ngIf="isLoggedIn" 
        mdbWavesEffect>

            Profile<span class="caret"></span></a>

还有 CSS:

.notification[innerHTML]:after {
    position:absolute;
    right:86%;
    top:0%;
    content: attr(innerHTML);
    font-size:60%;
    padding:.6em;
    border-radius:999px;
    line-height:.75em;
    color: white;
    background:rgba(255,0,0,.85);
    text-align:center;
    min-width:2em;
    font-weight:bold;
}

当我尝试添加插值以使通知数量更动态地显示时,我得到以下结果:Result when adding interpolation

唯一的区别在于我的html:

 <li class="nav-item dropdown" dropdown>

  <span class="notification has-badge" innerHTML="{{testvar}}" 
   *ngIf="newNotificationsAvailable" >  </span>

       <a dropdownToggle mdbWavesEffect type="button" class="nav-link 
        dropdown-toggle waves-light fa fa-user" *ngIf="isLoggedIn" 
        mdbWavesEffect>

            Profile<span class="caret"></span></a>

唯一的区别是我的 innerHTML = {{testvar}} 而不是 4。

我对应的 .ts 文件只是将 testvar 设置为 5:

  export class AppComponent implements OnInit {

     public testvar = 5;


     //...plus a bunch of irrelevant code.
   }

谁能帮我理解为什么我的 css 对非静态值的响应不同?

【问题讨论】:

  • 看起来你想要ng-bind-html="testvar" 而不是那个innerHTML。

标签: javascript css angular


【解决方案1】:

您的第二个示例有效地导致&lt;span class="notification has-badge" &gt;&lt;/span&gt;

innerHTML="{{testvar}}" 导致 Angular 将 testvar 的值绑定到属性 innerHtml。因此,它有效地从 HTML 中删除了属性,因为该属性没有相应的属性。所以当浏览器尝试渲染content: attr(innerHTML);时,根本就没有这样的属性。

您可以使用title 属性来代替innerHTML,这样就可以了。或者您在 HTML 中包含该值。

【讨论】:

  • 谢谢!很好的解释,并且与 title 属性完美配合:)
【解决方案2】:

试试这个:

<span class="notification has-badge"
      *ngIf=newNotificationsAvailable && testvar">
  {{testvar}}
</span>

【讨论】:

  • 我认为您错误地添加了两个 *ngIf :-)
  • 错了..是的:-D
猜你喜欢
  • 2019-02-06
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
相关资源
最近更新 更多