【问题标题】:How to bind a multiple specific value from json file in Angular?如何从Angular中的json文件绑定多个特定值?
【发布时间】:2021-03-31 12:30:41
【问题描述】:

我正在尝试在 Angular 中做一个简单的@input 绑定过程。我做了大部分。我不知道为什么,但我无法获取数据。我认为我的 .map 使用有问题。

这是我的父组件.ts

export class DashboardContainerComponent implements OnInit {   cards: { title: string, body: string }[];

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get("https://jsonplaceholder.typicode.com/comments").subscribe((comments: any) => {
      cts
      // this.cards = comments. ... map? reduce? filter?
      this.cards = comments.map(n => {
        return {title: n["name"], body: n["body"] };
      } )  
    })   }

}

这是子组件.ts

export class MyCardComponent implements OnInit {

  @Input() item: {title: string, body: string}[];
  // TODO: define @Input(s) here
  
  constructor() { }

  ngOnInit(): void {
  }

}

这就是我在父组件中使用此绑定的方式。html

<div class="dashboard-container">
  <h1>Comments</h1>
  <ng-container *ngIf="!cards">
    <div class="info-text">Cards will appear here.</div> 
  </ng-container>
  
  <ng-container *ngFor="let card of cards">
    <!-- TODO: assign input(s) below in app-my-card -->
    <app-my-card [item]="cards"></app-my-card>
  </ng-container>
</div>

这就是我在子 component.html 中使用此绑定的方式

<div class="card-container">
  <div class="card-title">
    <h1>{{item.title}}</h1>
  </div>
  <div class="card-body">
    <p>{{item.body}}</p>
  </div>
</div>

【问题讨论】:

    标签: angular function binding components


    【解决方案1】:

    在您的子组件中,模板和 TS 文件之间关于什么是“项目”存在不一致 您的子组件应该接受一个项目,或者一个项目数组,但不能同时接受:

    • 调用你传递的子模板 [item]="cards",所以完整的数组
    • 在子 .ts 文件中,项目被声明为数组
    • 在子模板文件中,item 应该是一个带有 .title 和 .body 的对象,但它有一个数组(所以未定义)。

    这似乎是有道理的: 将输入输入为单个元素

    @Input() item: {title: string, body: string}; // <= no more array
    

    ...并将 *ngFor 中定义的元素传递给它(而不是整个数组)

    <ng-container *ngFor="let card of cards">
        <!-- TODO: assign input(s) below in app-my-card -->
        <app-my-card 
            [item]="card" // NOT cards 
        ></app-my-card>
      </ng-container>
    

    通过在您的子模板中添加类似这样的调试内容来了解​​正在发生的事情

    <pre>item : {{ item | json }} </pre> 
    

    【讨论】:

    • 非常感谢。我完全错过了卡片/卡片的情况。它解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多