【问题标题】:Angular 2 variable in template is undefined模板中的 Angular 2 变量未定义
【发布时间】:2017-05-19 18:48:41
【问题描述】:

我在我的组件中声明一个变量。

例如

let link = 'https://google.com'

但是如果我在我的模板中使用它,它就不存在了

例如

{{ link }} -> has no output
href="#{{link}}" -> resolved into href="#"
[attr.href]="link" -> resolves into nothing
[attr.href]="link+'#'" -> resolves into href="undefined/#"

我做错了什么?

感谢您的帮助

【问题讨论】:

    标签: angular href


    【解决方案1】:

    改变

    let link = 'https://google.com'
    

    link:string = 'https://google.com';
    

    这段代码

    let link = 'https://google.com'
    

    是一个语句,只能在构造函数或方法或函数中使用,但不能在只允许声明的类的顶层使用。

    【讨论】:

    • 这会在控制台中引发一些错误:'unused label' & 'cannot find name "string"' 我的 IDE 将 'link' 声明为:TS7028: Unused Label 和 'string' as: TS2304: Cannot查找名称“字符串”
    • 请发布更多代码。我们无法知道您的问题中的代码在您的应用程序中的哪个位置使用。
    • 好吧,我在这里犯了一个错误。我在构造函数中声明了它。我现在把它移出它,所以它现在可以工作了。非常感谢。
    【解决方案2】:

    应该是

    link = 'https://google.com'
    

    let的instedad

    let 仅用于块范围,要在模板中使用该变量,您必须声明该变量,

    PS:let 只能在方法/函数中使用

    有关let 的更多信息,请参见此处

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多