Angular 2如何创建嵌套结构?
我有一组表达式,当你选择一个表达式时,会创建一个新的表达式行,这个表达式是嵌套的.我创建了这个对象对象:
export class Expression { selector: string; constraint: string; value: string; children: Expression[]; } 因此,当选择此ConditionSet时,我想“移动”或将其复制到Expression.children.现在,如果我通过添加一个来调试this.log this.expressions,它看起来如下: 但是就像你看到中间选择框是嵌套的,并且arrivalDate必须嵌套在conditionSet.children中,如下所示: Expression { selector: "conditionSet",value:"" children: selector:"ArrivalDate",value:"" } 嵌套的addButton也必须将它推送到.children来创建嵌套内容. 我这样想,但这不起作用:(: if(this.expression.selector === 'conditionSet'){ this.prototypes = this.prototypes.children; console.log(this.prototypes); } 有人可以帮我解决这个问题,我真的对这个问题感到绝望. 这是PLUNKER 解决方法
实际上,您没有在ExpressionComponent类中定义addExpression方法,只能在ExpressionBuilderComponent类中定义.所以你只能为第一级添加表达式……
此外,我认为您没有正确管理数据的递归方面. 对于ExpressionBuilderComponent组件,您需要为表达式组件的expressions参数提供expresion.children数组: <expression *ngFor="#expression of expressions" [prototypes]="prototypes" [expression]="expression" [expressions]="expression.children"></expression> <button class="btn btn-primary" (click)="addExpression()">Add Expression</button> 必须对ExpressionComponent本身进行相同的操作: <div class="col-xs-3"> <select class="form-control" [(ngModel)]="selectedPrototypeSelector" (ngModelChange)="onPrototypeChange()"> <option *ngFor="#p of prototypes" [value]="p.selector"> {{ p.selectorName }} </option> </select> </div> <div *ngIf="prototype?.valueType === 'Set'"> <div [ngClass]="{'nested-expression': prototype?.valueType === 'Set'}"> <expression *ngFor="#expression of expressions" [prototypes]="prototypes" [expression]="expression" [expressions]="expression.children"></expression> <button class="btn btn-primary" (click)="addExpression()">Add Expression</button> </div> </div> 看到这个plunkr:https://plnkr.co/edit/zGcoZD?p=preview. 编辑 关于删除,您需要处理自定义事件(@Ouput)来执行此操作,因为您需要从父项的子项中删除该元素: <div class="col-xs-1"> <button class="btn btn-danger pull-right" (click)="deleteExpression()">Delete</button> </div> <div *ngIf="prototype?.valueType === 'Set'"> <div [ngClass]="{'nested-expression': prototype?.valueType === 'Set'}"> <expression *ngFor="#expression of expressions" [prototypes]="prototypes" [expression]="expression" [expressions]="expression.children" (expressionDeleted)="onExpressionDeleted(expression)"> </expression> <button class="btn btn-primary" (click)="addExpression()">Add Expression</button> </div> <div>{{expression | json}}</div> </div> 在组件中: export class ExpressionComponent implements OnInit { (...) @Output() expressionDeleted: EventEmitter = new EventEmitter; (...) deleteExpression() { this.expressionDeleted.emit(); } onExpressionDeleted(expression) { var index = this.expressions.indexOf(this.expression); this.expressions.splice(index,1); console.log(index); } } 请参阅此plunkr以进行删除:https://plnkr.co/edit/rQCILc?p=preview. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |