Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 角度2:手动引导组件不属于包含数据的根组件_Angularjs_Angular_Angular2 Directives - Fatal编程技术网

Angularjs 角度2:手动引导组件不属于包含数据的根组件

Angularjs 角度2:手动引导组件不属于包含数据的根组件,angularjs,angular,angular2-directives,Angularjs,Angular,Angular2 Directives,除了主引导应用程序之外,我还有一个组件要初始化和呈现 例如,在react中,我可以做如下操作: var div = document.createElement('div'); React.render(React.createElement(MyComponent, { }), div); constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) { this.data = elementRef.nativeElem

除了主引导应用程序之外,我还有一个组件要初始化和呈现

例如,在react中,我可以做如下操作:

var div = document.createElement('div');
React.render(React.createElement(MyComponent, { }), div);
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
  this.data = elementRef.nativeElement.attributes['data'];
}
我希望能够在Angular 2中用一个组件做类似的事情

此外,我意识到,从角度来看,这些组件也可能被视为指令。我不太确定在这个场景中是否应该使用指令或组件术语

下面是我现在所做工作的示例代码(我已尝试尽可能地精简):

导出接口Tweet{
id:编号;
文本:字符串;
}
@组成部分({
选择器:“tweet”,
模板:`
{{tweet.text}
`,
输入:['tweet']
})
导出类tweet组件{
公共推文:推文;
}
//当在另一个组件的模板上下文中(如:
//手动初始化的代码
var tweetEl=document.createElement('tweet');
var body=document.querySelector('body');
附体儿童(tweetEl);
var comp=新的TweetComponent();
comp.tweet=tweet;
引导(TweetComponent,[provide(TweetComponent,{useValue:comp})]);
现在,它给了我以下错误:

异常:TypeError:无法读取中未定义的属性“text” {{tweet.text}}在TweetComponent中]


您可以运行引导两次

bootstrap(ComponentA);
bootstrap(ComponentB);

这是我现在的方法,直到有人给出更好的答案

首先,将目标组件拆分为一个基本组件,然后再拆分为两个子组件,一个类似于原始组件,第二个类似于构造函数:

var div = document.createElement('div');
React.render(React.createElement(MyComponent, { }), div);
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
  this.data = elementRef.nativeElement.attributes['data'];
}
然后,要手动引导组件,请执行以下操作:

var el = document.createElement('myselector');
el.attributes['data'] = data;
var body = document.querySelector('body');
body.appendChild(el);
bootstrap(MyComponent)

有没有办法通过这种方式传递参数?组件依赖于模型实例。另外,如果能够指定要对其运行的DOM元素,而不是对整个DOM运行,那就太好了。它是“针对”组件在其
@component({selector:'comp-a',…})中包含的选择器运行的(
)。您可以使用
bootstrap(ComponentA,[provide(Config,{useValue:new Config('someValue')})])中的providers列表传递参数。
grrr,不幸的是,它似乎没有正确初始化组件。即使我实例化了组件并为其设置了适当的值,在模板中,它也无法从组件实例获得正确的公共属性。仍在挖掘…请添加演示您所做操作的代码。我敢肯定,如果做得好,这一切都会很好。看起来你是在尝试类似react或来自react的背景,这是相当疯狂的,这是不可能的,也不容易。仅供参考,DynamicComponentLoader在2.0发布之前已被删除