两个组件如何相互引用

时间:2016-04-20 20:00:16

标签: angular angular2-template angular2-directives

我有角度为2的两个组件.ContainerOne和ContainerTwo

ContainerOne引用ContainerTwo,ContinerTwo在我们的指令中引用ContainerOne:[]

错误是:

  

未捕获(承诺):意外的指令值'undefined'   组件'ContainerTwo'的视图

第一课:

import {Component, Input} from 'angular2/core';
import {ContainerTwo} from './container-two';

@Component({
  selector: 'container-one'
, template: '
<div *ngIf="level > 0" 
    style="width: {{level * 20}}px; 
    height: {{level * 20}}px; 
    background-color: red;">

  <container-two [level]="level - 1"></container-two>

</div>'
, directives: [ContainerTwo]
})
export class ContainerOne {

    @Input() level: number;

    constructor() {
    }
}

第二类:

import {Component, Input} from 'angular2/core';
import {ContainerOne} from './container-one';

@Component({
  selector: 'container-two'
, template: '
<div *ngIf="level > 0" 
  style="width: {{level * 20}}px; 
  height: {{level * 20}}px; 
  background-color: blue;">

    <container-one [level]="level - 1"></container-one>

</div>'
, directives: [ContainerOne]
})
export class ContainerTwo {

    @Input() level: number;

    constructor() {
    }
}

app.ts:

import { Component } from 'angular2/core';
import {ContainerOne} from './container-one';
import {ContainerTwo} from './container-two';

@Component({
  selector: 'app'
, template: '<container-one [level]="10"></container-one>'
, directives: [ContainerOne, ContainerTwo]
})
export class App {

    constructor() {
    }
}

(它是我问题的骨架,真正的容器更复杂,而且不相似) 此示例程序想要在级别&gt;之间绘制一些div。 0

有什么问题?也许是参考圈?你知道吗?

1 个答案:

答案 0 :(得分:0)

是的,参考周期。每个*.ts文件都是一个模块(大部分时间),但模块是逐个加载的,并且不会自动处理循环依赖项。您应该使用forwardRef来打破此周期,请检查此link