我有两个Angular2组件,一个是“Main”和“Another”。从“Main”,我导航到“Another”,在其模板中引用了其他组件,如下面的模板示例:
<div>
Some other templates and HTML...
<person>Loading person...</person>
</div>
问题是如果以这种方式使用,person
组件必须被引导,但引导它将导致选择器匹配错误。这是有道理的,因为HTML模板尚未呈现。
如何实现这一目标?
更新
以下是示例代码:
主要
import {Component, provide} from 'angular2/core';
import {RouteConfig, Router, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router';
import {Another} from './Another';
@RouteConfig([
{ path: '/Another', name: 'Another', component: Another}
])
@Component({
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS],
selector: 'Main',
template:
'<div>
<button type="button" (click)="navigate()">Navigate</button>
<router-outlet></router-outlet>
</div>'
})
export class Main {
constructor(private _router: Router) { }
navigate() {
this._router.navigate(['Another']);
}
}
另一个
import {Component} from 'angular2/core';
@Component({
selector: 'Another',
template:
'<div>
<h1>i'm another!</h1>
<!-- how do I use this here? -->
<person>Loading person...</person>
</div>'
})
export class Another {
}
人
import {Component} from 'angular2/core';
@Component({
selector: 'person',
template:
'<div
<h1>i'm person!</h1>
</div>'
})
export class Person {
}
同样,如果我在根组件中引导person
,我将得到'选择器与元素不匹配'错误。
更新2
将directives: [Person]
添加到“另一个”组件将导致以下错误:“预计不在角度区域中,但它是!”,但“人物”的模板确实呈现。
答案 0 :(得分:1)
如果我理解你想做什么,试试这个。
import {Component} from 'angular2/core';
import {Person} from 'path-to-person-component';
@Component({
selector: 'Another',
template:
'<div>
<h1>i'm another!</h1>
<!-- how do I use this here? -->
<person>Loading person...</person>
</div>',
directives: [Person]
})
export class Another {
}