Search code examples
arraysangularangular-materialangular-cdkangular-cdk-drag-drop

Weird ouput when displaying an array in Angular


i am making a todo app in Angular with Angular Material. I made it so i have 2 inputs field for a todo, title and description. they get put into an array and this array is displayed in a cdkDropList. when i write something into the input fields my output in the cdkDropList is like this: {"title":"Go with the Dog","description":"Walk the Dog"}

This is my .ts:

import { Component } from '@angular/core';
import { AppModule } from '../app.module';
import { CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

interface Todo {
  title: string;
  description: string;
}

@Component({
  selector: 'app-todos',
  templateUrl: './todos.component.html',
  styleUrls: ['./todos.component.scss']
})
export class TodosComponent {
  done = [];
  title!: string;
  description!: string;
  todo: Todo[] = [];
  addTodo() {
    if (this.title && this.description) {
      this.todo.push({ title: this.title, description: this.description });
      this.title = '';
      this.description = '';
    }
  }
  drop(event: any) {
   if (event.previousContainer === event.container) {
    moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
   } else {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex,
    );
   }
  }
}


and this my .html:

<div class="input-container">
  <mat-form-field>
    <input matInput placeholder="Titel" [(ngModel)]="title">
  </mat-form-field>
  <mat-form-field>
    <input matInput placeholder="Beschreibung" [(ngModel)]="description">
  </mat-form-field>
  <button mat-raised-button color="primary" (click)="addTodo()">Hinzufügen</button>
</div>

<div class="example-container">
  <h2>To do</h2>

<div
  cdkDropList
    #todoList= "cdkDropList"
    [cdkDropListData]="todo"
    [cdkDropListConnectedTo]="[doneList]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of todo" cdkDrag>{{item | json}}</div>
  </div>
</div>

<div class="example-container">
  <h2>Done</h2>

  <div
    cdkDropList
    #doneList= "cdkDropList"
    [cdkDropListData]="done"
    [cdkDropListConnectedTo]="[todoList]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of done" cdkDrag>{{item | json}}</div>
  </div>
</div>```



The ouput should be:
Go with the dog 
Walk the Dog.

With the linebreak if possible 

Solution

  • it's because you are showing its Json form. you can access the value of data like this:

    <div class="example-box" *ngFor="let item of todo" cdkDrag>{{item.title}} {{item.description}}</div>