使用属性初始化Angular 2组件 [英] Initialize Angular 2 component with attribute
问题描述
是否可以将参数pas到Angular 2组件的根?我已经能够使用内部组件模板中的组件来执行此操作,而不能使用根组件来做到这一点:
Is there any way to pas parameters to the root of an Angular 2 Component? I have been able to do this with the components that are part of the internal component template but not with the root component:
<my-component [test] = "some-val"></my-component>
在我的组件上:
export class AppComponent implements OnInit {
test: string;
ngOnInit() {
console.log(this.test); //test is undefined
}
}
这样做的原因是使用Razor变量传递给Angular.例如,编辑用户.我可以做类似的事情:
The reason to do this is use Razor variables to be pass to Angular. Like editing a user for instance. I could do something like:
<edit-form [model] = "@Model.Id" > </edit-form>
推荐答案
Angular仅从其他组件内部不对index.html
进行任何绑定.
Angular does not do any binding from index.html
only from within other components.
一种在根组件中获取属性值的解决方法是
A workaround to get attribute values in the root component is
export class AppComponent {
constructor(elementRef:ElementRef) {
console.log(elementRef.nativeElement.getAttribute('inputField));
}
}
另请参见 https://github.com/angular/angular/issues/1858
这篇关于使用属性初始化Angular 2组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!