根指令上的Angular 2输入参数

red*_*man 14 typescript angular2-template angular

示例显示如何在子组件上使用@Input()批注.我的问题是你如何在根组件上使用它?例如,如果您修改上面链接上的代码:

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

bootstrap(App);
Run Code Online (Sandbox Code Playgroud)

并在HTML中:

<app something="Test"></app>
Run Code Online (Sandbox Code Playgroud)

上面的示例永远不会更新App组件上的某些属性.

mar*_*tin 21

我想你仍然可以使用:

class App {
    constructor(elm: ElementRef) {
        this.something = elm.nativeElement.getAttribute('something'); 
    }
}
Run Code Online (Sandbox Code Playgroud)


ale*_*ods 20

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

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

所以,此时你不能在根元素上使用输入参数.