gpt4 book ai didi

recursion - Angular2递归组件

转载 作者:太空狗 更新时间:2023-10-29 17:38:35 24 4
gpt4 key购买 nike

我正尝试按照这些帖子和 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com