2017-06-27 61 views
0

我正在嘗試創建一個樹結構,其中根節點被命名爲「或」。它應該有「AND」節點作爲它的子節點,反過來應該有「OR」節點作爲它的子節點,等等...... 有人能告訴我這段代碼有什麼問題嗎?angular2數組推對象in對象

import {Component} from '@angular/core' 
@Component({ 
    selector: 'my-app', 
    template: ` 
     <div *ngFor="let i of data1"> 
      {{i.name}} 
      <button (click)="add(i)">Add node</button> 
      <button *ngIf="i.categories.length >0" (click)="delete(i)">Delete 
       nodes</button> 
      <ul> 
       <li *ngFor="let item of i.categories"> 
        <my-app></my-app> 
       </li> 
      </ul> 
     </div> 
    ` 
}) 
export class AppComponent { 
    name:string; 
    key: string = 'categories'; 
    data1 = [ 
     { 
      name: "OR", 
      categories: [] 
     }, 
    ]; 

    add(data){ 
     var newName = data.name="AND"? "OR" : "AND" 
     var entry = { name: newName, categories: []} 
     data.categories.push(entry); 
    } 

    delete(data) { 
     data.categories = []; 
    }; 
} 
+0

我不知道,什麼不是工作?當你用調試器跟蹤它時會發生什麼?你有運行時錯誤嗎?編譯時錯誤?或者它運行的結果不正確? –

回答

0

這裏是你想達到什麼一個plnkr演示。

通過使用遞歸,您正處於正確的道路上,您只需將新類別Input傳遞給my-app組件,以便它可以呈現它。

下面是組件的完整代碼:

@Component({ 
    selector: 'my-app', 
    template: ` 
     <div> 
     {{dataRef.name}} 
     <button (click)="add(dataRef)">Add node</button> 
     <button *ngIf="dataRef.categories.length >0" (click)="delete(dataRef)">Delete 
     nodes</button> 
     <ul> 
      <li *ngFor="let item of dataRef.categories"> 
       <!-- you just needed to pass dataRef to keep track of categories --> 
       <my-app [dataRef]="item"></my-app> 
      </li> 
     </ul> 

     </div>` 
}) 
export class AppComponent implements OnInit { 
    @Input() dataRef: any; 

    name: string; 
    key: string = 'categories'; 
    // I don't think we need an array, an object would suffice 
    data1 = { 
     name: "OR", 
     categories: [] 
    }; 

    constructor() { 

    } 

    ngOnInit() { 
     console.log("old", this.dataRef); 
     // use this.data1 for the first time as this.dataRef will be undefined 
     this.dataRef = this.dataRef || this.data1; 
     console.log("new", this.dataRef) 
    } 

    add(data) { 
     var newName = data.name === "AND" ? "OR" : "AND" 
     var entry = { name: newName, categories: []} 
     data.categories.push(entry); 
    } 


    delete(data) { 
     data.categories = []; 
    }; 
} 
+0

Thanx,工作... 只是想知道應該做什麼改變,如果我想在每個節點旁邊的刪除按鈕,當它產生,並會導致刪除該節點本身 – NoobCoder

0

應該DATA1,而不是數據

add(data){ 
    var newName = data.name==="AND"? "OR" : "AND"; 
    var entry = { name: newName, categories: []} 
    data1.categories.push(entry); 
} 
+1

'data.name ===「AND」? 「OR」:「AND」也是三元操作符。 – CozyAzure

+0

我想添加一個新的對象,其中作爲參數傳遞的數據對象的類別 – NoobCoder

+0

不能將對象添加到對象 – Sajeetharan