You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中展示Todo数组时出现异常JSON格式输出问题求助

解决方法

问题根源是你使用了| json管道将整个Todo对象序列化为JSON字符串,导致展示成对象格式。只需手动渲染title和description属性并添加换行即可实现需求。

步骤1:修改模板渲染逻辑

将两处{{item | json}}替换为直接渲染属性的代码,以下提供两种实现方式:

方式1:用<br>快速换行
<div class="example-box" *ngFor="let item of todo" cdkDrag>
  {{item.title}}<br>
  {{item.description}}
</div>
方式2:用嵌套div(更便于样式定制)
<div class="example-box" *ngFor="let item of todo" cdkDrag>
  <div class="todo-title">{{item.title}}</div>
  <div class="todo-description">{{item.description}}</div>
</div>

注意:Done列表的模板需要做完全相同的修改,确保两个列表的展示效果一致。

步骤2:可选样式优化(提升视觉层次)

在组件的scss文件中添加样式:

.todo-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.todo-description {
  color: #666;
  font-size: 0.9em;
}

修改后的完整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>
      <div class="todo-title">{{item.title}}</div>
      <div class="todo-description">{{item.description}}</div>
    </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>
      <div class="todo-title">{{item.title}}</div>
      <div class="todo-description">{{item.description}}</div>
    </div>
  </div>
</div>

修改后即可实现你想要的换行展示效果:

Go with the dog
Walk the Dog

内容的提问来源于stack exchange,提问作者Bati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:35:27