14

This example shows how to use @Input() annotation on child components. My question is how do you use it on root component? For example if you modify code on the link above:

@Component({
selector: 'app',
template: `
    <bank-account bank-name="RBC" account-id="4747"></bank-account>
`,
directives: [BankAccount]
})
class App {
    @Input() something: string;
}

bootstrap(App);

And in html:

<app something="Test"></app>

The above example never updates something property on App component.

4

2 回答 2

23

我认为您仍然可以使用:

class App {
    constructor(elm: ElementRef) {
        this.something = elm.nativeElement.getAttribute('something'); 
    }
}
于 2016-02-22T12:26:24.570 回答
20

Tobias Bosch 的评论回答了您的问题:

这不起作用的原因是您放置的 index.html<app something="Test"></app>不是角度组件。因此,Angular 不会编译这个元素。Angular 不会在运行时读取属性值,只在编译时读取,否则我们会受到性能影响。

因此,此时您不能在根元素上使用输入参数。

于 2015-11-10T23:48:02.173 回答