首页 文章

在另一个导航组件中使用Angular2 typescript组件

提问于
浏览
1

我有两个Angular2组件,一个是“Main”和“Another” . 从“Main”,我导航到“Another”,在其模板中引用其他组件,如下面的模板示例:

<div>
    Some other templates and HTML...
    <person>Loading person...</person>
</div>

问题是如果以这种方式使用,则必须引导 person 组件,但是引导它将导致选择器匹配错误 . 这是有道理的,因为HTML模板尚未呈现 .

怎么可能实现这个目标?

Update

这是一个示例代码:

Main

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']);
    }
}

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 {

}

Person

import {Component} from 'angular2/core';

@Component({
    selector: 'person',
    template:
    '<div
        <h1>i'm person!</h1>
    </div>'
})
export class Person {

}

再次,如果我在根组件引导 person 我'll get '选择器没有't match element'错误 .

Update 2

directives: [Person] 添加到"Another"组件将导致以下错误:"Expected to not be in Angular Zone, but it is!",但'person'的模板确实呈现 .

1 回答

  • 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 {
    
    }
    

相关问题