繁体   English   中英

绑定到 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
  }
}

普朗克

我究竟做错了什么?

我正在试验 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”打印到控制台。

当前的方法是将属性装饰为@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

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

howYouReadInClass:howYouDefineInHtml

因此,您也可以执行以下操作:

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

  }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM