绑定到 angular2 中的组件 属性

Binding to a component property in angular2

我想在 A. 该组件的构造函数 B. 该组件的模板中引用组件上的 属性。这方面的 API 似乎有点变化,但我希望以下内容有效:

<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

我做错了什么?

我在试验 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 的 Class 上的属性。不确定这是有意还是错误。

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

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

将 'Matt' 打印到控制台。

其实,你可以做得更好。当您在组件中定义属性时,您总是按以下方式指定它:

howYouReadInClass:howYouDefineInHtml

所以,你不妨做以下事情:

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

  }
}

这样你就不会在 TS 中发生冲突,而且你的代码会更清晰——你将能够像在 partent 组件中定义变量那样定义变量。

目前的做法是将属性装饰成@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