Input decorator只能用在Angular class字段里, 用于指定元数据,将class字段指定成input property.
Decorator that marks a class field as an input property and supplies configuration metadata. The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property’s value.
参数名称:The name of the DOM property to which the input property is bound.
看个例子:
看个例子:
@Component({
selector: 'bank-account',
template: `
Bank Name: {{bankName}}
Account Id: {{id}}
`
})
class BankAccount {
// This property is bound using its original name.
@Input() bankName: string;
// this property value is bound to a different property name
// when this component is instantiated in a template.
@Input('account-id') id: string;
// this property is not bound, and is not automatically updated by Angular
normalizedBankName: string;
}
@Component({
selector: 'app',
template: `
<bank-account bankName="RBC" account-id="4747"></bank-account>
`
})
class App {}
子组件的模板里,显示bankName和id两个模型字段。
这两个字段,加上了@Input装饰器,表明其数据源,需要外部消费者传入(通常是消费这个子组件的父组件)
父组件的传值方式:
测试截图:
加了中括号后,表明等号右边的是一个表达式,不能当成普通字符串对待。
做个实验,如果删除子Component里的@Input:
最后什么也无法显示出来:
更多Jerry的原创文章,尽在:“汪子熙”: