【问题标题】:How to set the background image from the assets folder in Angular 8?如何从 Angular 8 的资产文件夹中设置背景图像?
【发布时间】:2020-06-06 13:00:44
【问题描述】:

我正在尝试从 assets 文件夹中设置我的 Angular 网站的背景图像。这是我的代码:

app.component.html

<div [style.background]="/assets/burn_calories.jpg"></div>
  <ul>
    <li><a href="default.asp">HOME</a></li>
    <li><a href="news.asp">PLAN</a></li>
    <li><a href="contact.asp">HISTORY</a></li>
    <li style="float:right"><a href="about.asp">LOGIN</a></li>
  </ul>

图片位于assets文件夹中

app.component.css

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    border: 1px solid #e7e7e7;
    background-color: #f3f3f3;
    position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 100%;
  }

  li {
    float: left;
    border-right: 1px solid #bbb;
  }

  li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
  }

  /* Change the link color to #111 (black) on hover */
  li a:hover {
    background-color: #111;
  }

  .active {
    background-color: #4CAF50;
  }

我假设必须在应用组件级别设置背景图像。我收到此错误:

未捕获的错误:模板解析错误:解析器错误:意外的令牌 / 在 [/assets/burn_calories.jpg] 中的第 1 列 ng:///AppModule/AppComponent.html@0:25 ("]/assets/burn_calories.jpg">

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果您使用方括号表示法设置文字值,则需要像编写 javascript 一样设置文字值 - 使用字符串表示法。

    <div [style.background]="'url(/assets/burn_calories.jpg)'"></div>
    

    如果你不使用字符串表示法,你是在告诉 Angular 它应该调用一个名为 url 的函数,传入参数 /assets/burn_calories.jpg,它不会编译。

    演示:https://stackblitz.com/edit/angular-uk5k5q

    【讨论】:

    • 还是不行。我没有得到背景
    • 对不起,我弄错了。在这种情况下,您确实需要使用括号表示法。在子组件或指令上设置输入值时不需要这样做,但在设置style. 属性时显然需要这样做。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多