2015-05-01 56 views
13

我想引用A.中的组件属性,该组件的构造函数B.该组件的模板。这个API的似乎是移一点点,但是我希望下面的工作:绑定到angular2中的组件属性

<my-component [greeting]="hello"></my-component> 


// my component.es6.js 
@Component({ 
    selector: 'my-component', 
    properties: { 
    'greeting': 'greeting' 
    } 
}) 
@View({ 
    template: '{{greeting}} world!' 
}) 
class App { 
    constructor() { 
    console.log(this.properties) // just a guess 
    } 
} 

Plunkr

我在做什么错?

+0

我不知道这是可能的角的当前版本。我探讨了'angular2_material'如何处理它,但是当我尝试这些技术时,它或者什么也不做,或者它们使用我的angular2中找不到的特性(从npm时刻开始)。 (1)'[md-button] [href]'是一个简单的例子,我发现简单地期望'tabIndex'(使用'hostProperties',而不是'属性')将被绑定到对象,但是在我的代码中,它永远不会。 (2)'md-radio-button'使用@Attribute,TypeScript不会为我编译(angular2/angular2没有导出的成员'Attribute')。 – Langdon

+0

@Langdon有趣,感谢您的调查!现在似乎事情有点不稳定,这是可以预料的。 –

回答

5

我正在试验Angular2,并提出了相同的问题。 然而,我发现下面的当前alpha版本(2.0.0-alpha.21)

@Component({ 
    selector: 'hello', 
    properties: {'name':'name'} 
}) 
@View({ 
    template:`<h1>Hello {{_name}}</h1>` 
}) 
class Hello { 
    _name: string; 

    constructor() { 
    console.log(this); 
    }; 

    set name(name){ 
    this._name = name; 
    } 
} 

@Component({ 
    selector: 'app', 
}) 
@View({ 
    template: 
    ` 
    <div> 
     <hello name="Matt"></hello> 
    </div> 
    `, 
    directives: [Hello] 
}) 
class Application { 
    constructor() { }; 
} 

bootstrap(Application); 

似乎传递给bootstrap的类属性被忽略的工作。不确定这是否意图或错误。

编辑:我刚刚从源代码构建Angular2并尝试使用@Attribute注释,它按照文档工作(但仅适用于嵌套组件)。

constructor(@Attribute('name') name:string) { 
    console.log(name); 
}; 

将“Matt”打印到控制台。

+0

新手:请参考@ N1mr0d的回答 –

1

其实,你可以做得更好。当你在你的组件定义属性,你总是将其指定方式如下:

howYouReadInClass:howYouDefineInHtml 

所以,你不妨做到以下几点:

@Component({ 
    selector: 'my-component', 
    properties: { 
    'greetingJS:greetingHTML' 
    } 
}) 
@View({ 
    template: '{{greeting}} world!' 
}) 
class App { 
set greetingJS(value){ 
this.greeting = value; 
} 
    constructor() { 

    } 
} 

这样你不会得到冲突TS ,并且您将拥有更清晰的代码 - 您将能够在您在partent组件中定义变量时定义变量。

2

当前的方法是装饰@Input属性。

@Component({ 
    `enter code here`selector: 'bank-account', 
    template: ` 
    Bank Name: {{bankName}} 
    Account Id: {{id}} 
    ` 
}) 
class BankAccount { 
    @Input() bankName: string; 
    @Input('account-id') id: string; 
    // this property is not bound, and won't be automatically updated by Angular 
    normalizedBankName: string; 
} 
@Component({ 
    selector: 'app', 
    template: ` 
    <bank-account bank-name="RBC" account-id="4747"></bank-account>`, 
    directives: [BankAccount] 
}) 
class App {} 
bootstrap(App); 

上面的例子是从https://angular.io/docs/ts/latest/api/core/Input-var.html

+0

工作完美,谢谢! –