在Angular 2中,子组件可以通过构造函数参数获取其父组件.例:
@Component({...})
export class ParentComponent {
...
}
@Component({...})
export class ChildComponent {
constructor(private parent: ParentComponent) { }
...
}
Run Code Online (Sandbox Code Playgroud)
父母和孩子的类型不同,这很好用.
但是,另一个典型的用例是树结构,其中每个树节点都显示为一个单独的组件.如果每个树节点组件都应该有权访问其父节点,我们该怎么办?我试过这个:
@Component({...})
export class TreeNodeComponent {
constructor(private parent: TreeNodeComponent) { }
...
}
Run Code Online (Sandbox Code Playgroud)
但是这会因以下运行时异常而失败:
EXCEPTION: Cannot instantiate cyclic dependency!
Run Code Online (Sandbox Code Playgroud)
我想原因是Angular 2注入组件本身而不是其父组件.
如何将angular注入组件的父组件,即使它们属于同一类型?
我正在反对的API为我提供了以下结构:
"data": [
{
"id": 5,
"name": "First name",
"parent": 0
},
{
"id": 1,
"name": "Second name",
"parent": 5
},
{
"id": 6,
"name": "Third name",
"parent": 1
},
{
"id": 15,
"name": "Fourth name",
"parent": 0
},
{
"id": 25,
"name": "Fifth name",
"parent": 5
}
]
Run Code Online (Sandbox Code Playgroud)
我希望围绕此构建一个树结构,使用ngFor它支持无限数量的子级别.
这是我到目前为止所尝试的:
<div *ngFor="let d1 of _dataList">
<ul *ngIf="d1.parent == 0">
<li>
{{d1.name}}
<ul *ngFor="let d2 of _dataList">
<li *ngIf="d2.parent == d1.id">{{d2.name}}</li>
</ul>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
这是有效的,但它很难看,我必须手动重复这个X级别的数据,从而留下硬编码限制.
如何优化此代码以支持无限级别 - …
我在Plunker中有一个Angular应用程序,因为我已经升级了我的应用程序以使用Angular 6和rxjs 6 ,所以它不再有效.
这是我的config.js档案:
var angularVersion;
if(window.AngularVersionForThisPlunker === 'latest'){
angularVersion = ''; //picks up latest
}
else {
angularVersion = '@' + window.AngularVersionForThisPlunker;
}
System.config({
//use typescript for compilation
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
paths: {
'npm:': 'https://unpkg.com/'
},
//map tells the System loader where to look for things
map: {
'ngx-duration-picker': 'https://unpkg.com/ngx-duration-picker@latest/bundles/ngx-duration-picker.umd.js',
'app': './src',
'@angular/core': 'npm:@angular/core'+ angularVersion + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + angularVersion + '/bundles/common.umd.js',
'@angular/common/http': …Run Code Online (Sandbox Code Playgroud) 我有这样的对象somethig:
{
id: 1,
text: "Main",
childText: [
{
id: 3,
text: "Child 1",
childText: [
{
id: 5,
text: "child 2"
childText: [
....
]
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
任何对象都可以childText知道如何显示吗?