【发布时间】:2016-06-10 03:29:27
【问题描述】:
我一直在寻找解决方案。我从@Input、@Query、dynamicContentLoader、@Inject、@Inject(forwardRef(()) 中尝试了很多不同的东西,但还没有弄清楚。
我的示例结构:
parent.ts
import {Component} from 'angular2/core';
@Component({
selector : 'my-app',
directives : [Child],
template : `<parent-component></parent-component>`
})
export class Parent
{
private options:any;
constructor()
{
this.options = {parentThing:true};
}
}
child.ts
import {Component} from 'angular2/core';
@Component({
selector : 'parent-component',
template : `<child-component></child-component>`
})
export class Child
{
constructor(private options:any) <- maybe I can pass them in here somehow?
{
// what I am trying to do is get options from
// the parent component at this point
// but I am not sure how to do this with Angular 2
console.log(options) <- this should come from the parent
// how can I get parent options here?
// {parentThing:true}
}
}
这是我当前在 DOM 中的 HTML 输出,所以这部分工作正常
<parent-component>
<child-component></child-component>
</parent-component>
问题总结:
如何将选项从父组件传递到子组件并在子构造函数中使用这些选项?
【问题讨论】:
-
简单绑定有什么问题?
@Input()在孩子和<child [someInput]="someOption"? -
我已经看过很多次了。这很可能是解决方案。问题是无论出于何种原因,我都不明白一切应该如何联系在一起。我用@Input 搞砸了一段时间。但我认为我很难理解所有发生的隐含的事情以及如何让它正常工作。
-
基本上我已经尝试了所有这些..
@Input, @Query, dynamicContentLoader, @Inject, @Inject(forwardRef(()但我无法让他们做我想做的事情。所以我并不是说他们不能。但或多或少,我尽量减少了我的问题,以显示我想要达到的最终结果类型。其中之一可能是解决方案。 -
刚刚看到,为什么需要它们在构造函数中可用?
-
查看我更新的答案,但为什么在构造函数中需要它?
标签: javascript angular