Angular 2 个根指令输入参数
Angular 2 input parameters on root directive
This 示例展示了如何在子组件上使用@Input() 注解。我的问题是你如何在根组件上使用它?例如,如果您修改上面 link 上的代码:
@Component({
selector: 'app',
template: `
<bank-account bank-name="RBC" account-id="4747"></bank-account>
`,
directives: [BankAccount]
})
class App {
@Input() something: string;
}
bootstrap(App);
并且在 html 中:
<app something="Test"></app>
上面的示例从不更新 App 组件上的 something 属性。
This Tobias Bosch's comment 已回答您的问题:
The reason why this is not working is that your index.html in which you place the <app something="Test"></app>
is not an angular component. Because of this, Angular won't compile this element. And Angular does not read attribute values during runtime, only during compile time, as otherwise we would get a performance hit.
因此,目前您不能在根元素上使用输入参数。
我认为你仍然可以使用:
class App {
constructor(elm: ElementRef) {
this.something = elm.nativeElement.getAttribute('something');
}
}
This 示例展示了如何在子组件上使用@Input() 注解。我的问题是你如何在根组件上使用它?例如,如果您修改上面 link 上的代码:
@Component({
selector: 'app',
template: `
<bank-account bank-name="RBC" account-id="4747"></bank-account>
`,
directives: [BankAccount]
})
class App {
@Input() something: string;
}
bootstrap(App);
并且在 html 中:
<app something="Test"></app>
上面的示例从不更新 App 组件上的 something 属性。
This Tobias Bosch's comment 已回答您的问题:
The reason why this is not working is that your index.html in which you place the
<app something="Test"></app>
is not an angular component. Because of this, Angular won't compile this element. And Angular does not read attribute values during runtime, only during compile time, as otherwise we would get a performance hit.
因此,目前您不能在根元素上使用输入参数。
我认为你仍然可以使用:
class App {
constructor(elm: ElementRef) {
this.something = elm.nativeElement.getAttribute('something');
}
}