recursion - Angular2递归组件

标签 recursion angular components forward-reference

我正尝试按照这些帖子和 plnkr 中的讨论部署递归组件:

How do I inject a parent component into a child component?

> `http://plnkr.co/edit/l7jsV0k7DbGJGXPFlSPr?p=preview`

Angular2 Recursive Templates in javascript

但是,所提供的解决方案仅处理组件对象本身,并没有解决组件应该实例化的 HTML 标记的问题。

子组件如何使用 <parent> ... </parent>其模板内的 html 标记?

我将非常感谢您的帮助,也许您可​​以提供一个 plunkr/fiddle。

最佳答案

仅使用模板无法获得所需的结果,因为循环依赖会导致:

EXCEPTION: Unexpected directive value 'undefined' on the View of component 'ChildComponent'

正如您在 this Plunker 上看到的那样这是出现问题的迹象(一般 DI 问题不是 Angular 问题)。

ParentComponent 依赖子组件:

import {Component} from 'angular2/core';
import {AppComponent} from './app.component';
import {ChildComponent} from './child.component'

@Component({
  selector: 'parent',
  template: `<p>parent</p>
  <child></child>`,
  directives: [ChildComponent]
})
export class ParentComponent {
  constructor() {}
}

ChildComponent 依赖parent 导致循环依赖:

import {Component} from 'angular2/core';
import {AppComponent} from './app.component';
import {ParentComponent} from './parent.component';

@Component({
  selector: 'child',
  template: `<p>child</p>
  <parent></parent>`,
  directives: [ParentComponent]
})
export class ChildComponent {
  constructor() {}
}

然而,您可以通过使用 DynamicComponentLoader 来实现这一点,正如您在 example 中看到的那样但请记住提供某种条件来停止无休止的组件渲染。在我的示例中,条件是父组件中的输入参数:

import {Component, Input} from 'angular2/core';
import {AppComponent} from './app.component';
import {ChildComponent} from './child.component'

@Component({
   selector: 'parent',
   template: `<p>parent</p>
   <child *ngIf="condition"></child>`,
   directives: [ChildComponent]
})
export class ParentComponent {
  constructor() {
  }

  @Input() condition: bool;
}

关于recursion - Angular2递归组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045332/

相关文章:

java - 显示 GUI 的问题

xml - 如何在 cq 对话框中动态使用下拉元素更改选项?

javascript - 使用测距选项生成零件号的最佳方法

javascript - JavaScript 中的递归调用不起作用?

java - 递归数三角形

javascript - 可视代码中的 Angular 文件资源管理器 - 添加/修改/包含强调项的索引

asp.net core 2.0 spa angular + 谷歌地图

c - 使用递归关系证明函数具有指数运行时间?

javascript - 如何避免使用 trackBy 函数避免为 nGFor 重建 DOM - Angular Firestore

ios - iOS 中用于创建选择器选项的组件