cosmichero2025
cosmichero2025

Reputation: 1029

Can't pass data down to angular child component in ngFor loop?

I'm trying to pass the data "testData" down to the child component 'multi-card' but when I attempt to do so it returns this error.

Uncaught Error: Template parse errors: Can't bind to 'data' since it isn't a known property of 'app-multi-card'

I'm new to angular so I'm pretty sure I'm missing something obvious.

Parent TS

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-information-general-multi',
  templateUrl: './information-general-multi.component.html',
  styleUrls: ['./information-general-multi.component.scss']
})
export class InformationGeneralMultiComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  testData = [
    {
      "name": "bingo"
    },
    {
      "name": "notta"
    }
  ]

}

Parent Template

    <div class='mdl-grid mdl-grid--no-spacing'>

  <div class='mdl-cell mdl-cell--6-col mdl-cell--8-col-tablet' *ngFor="let test of testData">
        <app-multi-card [data]="testData"></app-multi-card>
      </div>
    </div>

I haven't tried to call it in my child component am I supposed to import the data in child component or does that happen automatically?

Upvotes: 1

Views: 4410

Answers (4)

Avinash
Avinash

Reputation: 1243

By default all the properties of the component are accessible within the component, to expose the property in a parent component to child component you need to explicitly mention by adding a decorator @Input() infront of the property.
In your child-component.ts

import Input frm @angular/core.
@Input() data;

then you can access test which you are assigning in the parent-component.

<div class='mdl-cell mdl-cell--6-col mdl-cell--8-col-tablet' *ngFor="let test of testData">
    <app-multi-card [data]="test"></app-multi-card>
</div>

Upvotes: 1

Abel Valdez
Abel Valdez

Reputation: 2408

Put test instead testData in the following sentense and Add an @Input data decorator in app-multi-card component

<app-multi-card [data]="test"></app-multi-card>

Upvotes: 1

lifetimeLearner007
lifetimeLearner007

Reputation: 655

Use [data]="test" as follows:

<div class='mdl-cell mdl-cell--6-col mdl-cell--8-col-tablet' *ngFor="let test of testData">
        <app-multi-card [data]="testData"></app-multi-card>
      </div>

Also, in app-multi-card component ts file, have you given @Input() declaration for data property?

@Input() data = ''

Refer https://angular.io/guide/component-interaction

Upvotes: 2

wilovent
wilovent

Reputation: 1364

You have to use the decorator @Input() on a property called data in your child component. This property will be fed automatically by the binding.

Have a look in the documentation for this : https://angular.io/guide/component-interaction

Upvotes: 3

Related Questions