【问题标题】:Angular2 : passing property to nested componentAngular2:将属性传递给嵌套组件
【发布时间】:2015-08-19 02:04:31
【问题描述】:

我正在使用 Angular 2 开发一个简单的测试应用程序,但在将属性传递给嵌套组件时遇到问题。请参阅下面的源代码。嵌套组件中的模板呈现,但传递给嵌套组件的属性不呈现。渲染输出为:

这是一个。

然而,我希望如下:

这是一个测试。

浏览器控制台中不会产生错误。我还尝试在嵌套组件中使用properties: 'inputtext',因为视图中的名称保持不变,但这会在控制台中生成 Can't bind to ... 错误。至于 Angular2 版本,我使用的是最新的(Alpha-34)。

有什么建议吗?

index.html

<html>
  <head>
    <title>Angular 2 Test App</title>
    <script src="https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.87/traceur-runtime.js"></script>
    <script src="https://jspm.io/system@0.16.js"></script>
    <script src="https://code.angularjs.org/2.0.0-alpha.34/angular2.dev.js"></script>
  </head>
  <body>
    <h1>Welcome to my Angular 2 Test App</h1>
    <app></app>
    <script>System.import('app');</script>
  </body>
</html>

app.ts

import {Component, View, bootstrap} from 'angular2/angular2';

//nested component
@Component({
  selector: 'input-component',
  properties: ['inputtext:inputtext']
})
@View({ template: '<h1>This is a {{inputtext}}.</h1>'})
class inputComponent{}

// root app
@Component({ selector: 'app' })
@View({ 
  directives: [inputComponent], 
  template: '<input-component [inputtext]="test"></input-component>' 
})
class rootApp{}

bootstrap(rootApp);

【问题讨论】:

    标签: angular


    【解决方案1】:

    这是因为你没有在你的属性上绑定一个变量,你只是给它传递了一个文字值。在这种情况下,您需要删除方括号并像这样给出它:inputtext="test"。如果您使用方括号 angular2 将期望一个变量并尝试映射到它,这会给您未定义。

    另外请注意,当您定义一个属性时,如果您的控制器中的变量与您公开的属性同名,您可以使用缩写形式:

    properties: ['inputtext']
    

    【讨论】:

    • properties 上仍然没有真正的文档。这是一个真正的帮助!
    【解决方案2】:
    template: '<input-component [inputtext]="\'test\'"></input-component>'
    

    您的代码中的测试是一个未定义的变量。用引号括起来,它应该可以工作。

    【讨论】:

    • 这会导致错误:'Can't bind to 'inputtext' because it is not an known property of 'input-component'
    猜你喜欢
    • 1970-01-01
    • 2017-04-21
    • 2016-08-21
    • 2019-04-08
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多