簡體   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