(一)@Input属性讨论

@Input

Declares a data-bound input property.Angular automatically updates data-bound properties during change detection.

大概意思就是:@Input属性声明了一个数据绑定的输入属性,当angular检测到改变时可以自动更新。

在Angular2官方文档里有一段示例代码(https://angular.cn/docs/ts/latest/guide/ngmodule.html)

@Component({
  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: `
    
  `,
  directives: [BankAccount]
})
class App {}
bootstrap(App);
在网页上显示的内容:

Bank Name: RBC

Account Id: 4747

为BankAccount类声明了两个输入属性,并在标签中为其赋值。

在这里还要注意两点:

1)单向属性绑定

其中bank-name是视图目标,“RBC”是数据源,数据的流向是从数据源到视图目标。

如果输入属性不是字符串而是一个类,则注意要为视图目标加上[],比如:

2)@Input声明变量的两种形式

@Input() bankName: string;
@Input('bank-name'): string;
以上两种声明等效。


你可能感兴趣的:(Angular2学习笔记)