0
votes

I am trying to build chapter-topic tree in which chapter will be y main node and topics will be my child-node . i tried to build it but what problem i am facing is i am not able to edit or delete any node as i cannot find there level correctly. Can any one share a code with all operation.

   export class TodoItemNode {
  chapterTopicId: number;
  topicName: string;
  topics: TodoItemNode[];
}

/** Flat to-do item node with expandable and level information */
export class TodoItemFlatNode {
  chapterTopicId: number;
  topicName: string;
  level: number;
  expandable: boolean;
}

Here is main code:

export class ChapterTopicComponent implements OnInit {

  flatNodeMap = new Map<TodoItemFlatNode, TodoItemNode>();

  /** Map from nested node to flattened node. This helps us to keep the same object for selection */
  nestedNodeMap = new Map<TodoItemNode, TodoItemFlatNode>();

  /** A selected parent node to be inserted */
  selectedParent: TodoItemFlatNode | null = null;

  /** The new item's name */
  newItemName = '';

  clientGrades: any = [];
  clientSubjects: any = [];
  data: any = [];
  selectedGrade: string;
  selectedSubject: number;
  /**Current user value */
  user = JSON.parse(localStorage.getItem('currentUser'));

  topicName:string;

  treeControl: FlatTreeControl<TodoItemFlatNode>;

  treeFlattener: MatTreeFlattener<TodoItemNode, TodoItemFlatNode>;

  dataSource: MatTreeFlatDataSource<TodoItemNode, TodoItemFlatNode>;
  dataChange = new BehaviorSubject<TodoItemNode[]>([]);

  constructor(public dialog: MatDialog, private backendService: BackendService) {
    this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel,
      this.isExpandable, this.getChildren);
    this.treeControl = new FlatTreeControl<TodoItemFlatNode>(this.getLevel, this.isExpandable);
    this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
    this.dataChange.subscribe(data => {
      this.dataSource.data = data;
    });
  }

  ngOnInit() {
    this.getClientGrades();
    this.getClientSubjects();
  }

  getLevel = (node: TodoItemFlatNode) => node.level;

  isExpandable = (node: TodoItemFlatNode) => node.expandable;

  getChildren = (node: TodoItemNode): TodoItemNode[] => node.topics;

  hasChild = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.expandable;

  hasNoContent = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.topicName === '';

  /**
   * Transformer to convert nested node to flat node. Record the nodes in maps for later use.
   */
  transformer = (node: TodoItemNode, level: number) => {
    const existingNode = this.nestedNodeMap.get(node);
    const flatNode = existingNode && existingNode.topicName === node.topicName
      ? existingNode
      : new TodoItemFlatNode();
    flatNode.chapterTopicId = node.chapterTopicId;
    flatNode.topicName = node.topicName;
    flatNode.level = level;
    flatNode.expandable = !!node.topics?.length;
    this.flatNodeMap.set(flatNode, node);
    this.nestedNodeMap.set(node, flatNode);
    return flatNode;
  }

  // /** Whether all the descendants of the node are selected. */
  // descendantsAllSelected(node: TodoItemFlatNode): boolean {
  //   const descendants = this.treeControl.getDescendants(node);
  //   const descAllSelected = descendants.length > 0 && descendants.every(child => {
  //     return this.checklistSelection.isSelected(child);
  //   });
  //   return descAllSelected;
  // }

  // /** Whether part of the descendants are selected */
  // descendantsPartiallySelected(node: TodoItemFlatNode): boolean {
  //   const descendants = this.treeControl.getDescendants(node);
  //   const result = descendants.some(child => this.checklistSelection.isSelected(child));
  //   return result && !this.descendantsAllSelected(node);
  // }

  // /** Toggle the to-do item selection. Select/deselect all the descendants node */
  // todoItemSelectionToggle(node: TodoItemFlatNode): void {
  //   this.checklistSelection.toggle(node);
  //   const descendants = this.treeControl.getDescendants(node);
  //   this.checklistSelection.isSelected(node)
  //     ? this.checklistSelection.select(...descendants)
  //     : this.checklistSelection.deselect(...descendants);

  //   // Force update for the parent
  //   descendants.forEach(child => this.checklistSelection.isSelected(child));
  //   this.checkAllParentsSelection(node);
  // }

  // /** Toggle a leaf to-do item selection. Check all the parents to see if they changed */
  // todoLeafItemSelectionToggle(node: TodoItemFlatNode): void {
  //   this.checklistSelection.toggle(node);
  //   this.checkAllParentsSelection(node);
  // }

  // /* Checks all the parents when a leaf node is selected/unselected */
  // checkAllParentsSelection(node: TodoItemFlatNode): void {
  //   let parent: TodoItemFlatNode | null = this.getParentNode(node);
  //   while (parent) {
  //     this.checkRootNodeSelection(parent);
  //     parent = this.getParentNode(parent);
  //   }
  // }

  // /** Check root node checked state and change it accordingly */
  // checkRootNodeSelection(node: TodoItemFlatNode): void {
  //   const nodeSelected = this.checklistSelection.isSelected(node);
  //   const descendants = this.treeControl.getDescendants(node);
  //   const descAllSelected = descendants.length > 0 && descendants.every(child => {
  //     return this.checklistSelection.isSelected(child);
  //   });
  //   if (nodeSelected && !descAllSelected) {
  //     this.checklistSelection.deselect(node);
  //   } else if (!nodeSelected && descAllSelected) {
  //     this.checklistSelection.select(node);
  //   }
  // }

  /* Get the parent node of a node */
  getParentNode(node: TodoItemFlatNode): TodoItemFlatNode | null {
    const currentLevel = this.getLevel(node);

    if (currentLevel < 1) {
      return null;
    }

    const startIndex = this.treeControl.dataNodes.indexOf(node) - 1;

    for (let i = startIndex; i >= 0; i--) {
      const currentNode = this.treeControl.dataNodes[i];

      if (this.getLevel(currentNode) < currentLevel) {
        return currentNode;
      }
    }
    return null;
  }

  /** Get client grades */
  getClientGrades() {
    this.backendService.getClientGrades(this.user.clientId, this.getCurrentYear()).subscribe(data => {
      this.clientGrades = data;
    });
  }

  /** Get client subjects */
  getClientSubjects() {
    this.backendService.getClientSubjects(this.user.clientId).subscribe(data => {
      this.clientSubjects = data;
    });
  }

  /** Get selected grade */
  onGradeSelection(grade: string) {
    this.selectedGrade = grade;
    if (this.selectedGrade != null && this.selectedSubject != null) {
      this.loadData(this.selectedGrade, this.selectedSubject);
    }
  }

  /** Get selected subject */
  onSubjectSelection(subject: number) {
    this.selectedSubject = subject;
    if (this.selectedGrade != null && this.selectedSubject != null) {
      this.loadData(this.selectedGrade, this.selectedSubject);
    }
  }
  /** Load chapter and topic of selected grade and selected subject */
  loadData(grade: string, subjectId: number) {
    this.backendService.getClientChapterTopics(this.user.clientId, grade, subjectId).subscribe(res => {
      this.data = res;
      this.dataChange.next(this.data);

    });

  }

  /** Get current year */
  getCurrentYear() {
    return new Date().getFullYear();
  }

  /** Refresh grade and subject */
  RefreshGradeSubject() {
    this.getClientGrades();
    this.getClientSubjects();
  }

  /** Add an item to to-do list */
  insertItem(parent: TodoItemNode, name: string) {
    if (parent.topics) {
      parent.topics.push({ topicName: name } as TodoItemNode);
      this.dataChange.next(this.data);
    }
  }

  updateItem(node: TodoItemNode, name: string) {
    if (name.length > 0) {
      node.topicName = name;
      this.dataChange.next(this.data);
    }
  }

  /** Select the category so we can insert the new item. */
  addNewItem(node: TodoItemFlatNode) {
    const parentNode = this.flatNodeMap.get(node);
    this.insertItem(parentNode!, '');
    this.treeControl.expand(node);
  }

  /** Save the node to database */
  saveNode(node: TodoItemFlatNode, itemValue: string) {
    if (itemValue.length > 0) {
      let parentNode = this.getParentNode(node);
      this.backendService.postTopic(itemValue,this.selectedSubject, this.selectedGrade, parentNode.chapterTopicId, this.user.clientId)
        .subscribe(response => {
          const nestedNode = this.flatNodeMap.get(node);
          this.updateItem(nestedNode!, itemValue);
          console.log(response);
        }, (error: string) => {
          console.log("error" + error);
        });

    }
  }
  findPosition(id: number, data: TodoItemNode[]) {
    for (let i = 0; i < data.length; i += 1) {
      
      if (id === data[i].chapterTopicId) {
        return i;
      }
    }
  }

  /** Edit node */
  editNode(node: TodoItemFlatNode){
    let parentNode = this.getParentNode(node);
    let topicName = this.openDialog();
    if(topicName.length>0){
    if(parentNode===null){
      this.backendService.putChapter(topicName, this.selectedSubject, this.selectedGrade, this.user.clientId).subscribe(response =>{
        node.topicName = this.topicName;
        this.dataChange.next(this.data);
      });
    }else{
      this.backendService.putTopic(topicName, this.selectedSubject, this.selectedGrade, parentNode.chapterTopicId, this.user.clientId).subscribe(response =>{
        node.topicName= this.topicName;
        this.dataChange.next(this.data);
      });
    }
  }
  }

  openDialog() {
    let topic:string;
    const dialogRef = this.dialog.open(AddChapterDialogComponent, {
      width: '300px',
      data:{topicName: this.topicName}
    });

    dialogRef.afterClosed().subscribe(result =>{
      topic = result;
    }); 
    return topic;
  }

}

Here u can check pic what output i want.My data is coming and i can add new topic but i am not able to edit or delete it as i am not having level. At chapter if i click on plus button i can add topic,but if i click on edit or delete i suppose to get level so that i can change data.I am getting Id but not level.