【问题标题】:Angular2 timer with dynnamic image url - Got interpolation ({{}}) where expression was expected具有动态图像 url 的 Angular2 计时器 - 得到了预期表达式的插值 ({{}})
【发布时间】:2017-10-31 02:44:21
【问题描述】:

我有一个从 1 到 3 循环的计时器,在每个循环中,我想使用该数字在 url 中加载具有该数字的图像。

组件

    import { Component, OnInit, OnDestroy} from "@angular/core";
    import { Observable } from 'rxjs/Observable';
    import { Subscription } from "rxjs";

    @Component({
        selector: 'animated-content',
        template: require('./animated-content.template.html')
    })

    export class AnimatedContentComponent implements OnInit{

        highlightedItem = 1;
        private sub: Subscription;

        constructor(){

        }

        ngOnInit(){
            let timer = Observable.timer(1,2000);
            this.sub = timer.subscribe( t => this.startContentCycle(t))
        }

        private startContentCycle(highlightedItem) {
            if (this.highlightedItem === 3) {
                this.highlightedItem = 1;
            } else {
                this.highlightedItem++;
            }
        }

    }

模板

    <img [src]="/assets/signup-step{{highlightedItem}}.gif" alt="" class="img-responsive">

在资产中,图像是signup-step1.gifsignup-step2.gifsignup-step3.gif

我收到此错误:

'在期望表达式的地方得到插值({{}})'

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    正确的语法是这样的:

      <img [src]="'/assets/signup-step' + highlightedItem + '.gif'" alt="" class="img-responsive">
    

    您不能同时使用插值和数据绑定。

    【讨论】:

    • 是的,@OP:在这种情况下,最好在函数中提取这些内容 - 这将允许您使用 TS/ES6 字符串插值并使 html 更清晰
    猜你喜欢
    • 2017-07-16
    • 2019-08-04
    • 2017-03-05
    • 2017-03-04
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多