javascript - Angular 2 绑定(bind)属性

标签 javascript angular

我正在学习 Angular2,为此我正在创建一个示例代码。

我有一个可重用的组件Card,它应该接收一个参数:

import { Component, Input } from '@angular/core'

@Component({
  selector: 'card',
  templateUrl: '../templates/card.html'
})

export class Card {
    @Input() title;
}

该标题参数应该是一个字符串

这是迄今为止该组件的 html 模板:

<div class='card'>
  {{ title }}
  <ng-content></ng-content>
</div>

在其他组件中我这样调用它:

<card
  [title]='Enter your raw json'>
  Example
</card>

我在控制台中收到此错误(还有很多其他错误):

EXCEPTION: Template parse errors:
Parser Error: Unexpected token 'your' at column 7 in [Enter your raw json] in JsonTextInput@1:2 ("<card
  [ERROR ->][title]='Enter your raw json'>
  Example
</card>"): JsonTextInput@1:2

属性绑定(bind)有什么问题?

最佳答案

当您使用属性绑定(bind)时,Angular2 的模板解析器会将内容解释为组件类的属性:

@Component({
  template: `<card [title]="property"> ... </card>`,
  ...
})
class SomethingComponent {
  property = 'something'; // this will be bound to the title input of card
}

如果要将字符串文字传递给属性绑定(bind),请将其放在单引号内,如下所示:

[title]="'some title'"

关于javascript - Angular 2 绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37446338/

相关文章:

javascript - JS事件注册而不是onclick...但是如何使其可重用?解析ID?

javascript - 防止文本区域垂直滚动

node.js - 如何使用 Angular2 将 Blob 图像发送到 NodeJs?

java - 如何使用 Angular nativeScript Bootstrap 在 Android 上扩展应用程序类

javascript - 如何从 AgEditorComponent 的上下文中聚焦 ag-grid Angular 中的下一个单元格

javascript - 函数在 jQuery 中运行多次

javascript - 运行基本 Express 项目时出错

c# - 从 MVC 5 下载文件到 Angular 2

angular - 如何在 Angular 7 中从 ckeditor 5 检索数据?

angularjs - 没有 TemplateRef 的提供者! (ng2 Bootstrap )