【问题标题】:Binding to a component property in angular2绑定到angular2中的组件属性
【发布时间】:2015-07-11 12:48:26
【问题描述】:

我想引用 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

我做错了什么?

【问题讨论】:

  • 我不确定当前版本的 Angular 是否可行。我四处看看angular2_material 是如何处理它的,但是当我尝试这些技术时,它要么什么也没做,要么它们使用了我的 angular2 中没有的功能(刚才从 npm 中提取)。 (1) [md-button][href] 是我发现的一个简单示例,它只期望 tabIndex(使用 hostProperties,而不是 properties)将绑定到对象,但在我的代码中,它永远不会。 (2) md-radio-button 使用@Attribute,TypeScript 不会为我编译(angular2/angular2 没有导出的memember 'Attribute')。
  • @Langdon 很有趣,感谢您的调查!现在情况似乎有些不稳定,这是意料之中的。

标签: javascript ecmascript-6 angular


【解决方案1】:

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

【讨论】:

  • 新人:请参考@N1mr0d的回答
【解决方案2】:

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

howYouReadInClass:howYouDefineInHtml

所以,你也可以这样做:

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

  }
}

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 1970-01-01
      • 2017-04-28
      • 2015-09-28
      • 2016-07-26
      • 2016-03-28
      • 1970-01-01
      • 2016-12-21
      相关资源
      最近更新 更多