Array of component with a constructor and HTML and CSS files. error NG2003. ngFor

Viewed 62

My Problem: I created a CardComponent acts like a card view with css and html and has a constructor.

I want to use it in a cards array (of its type). I use service to store the cards' data.

home comp. is using the service and loop over with ngFor, This is the code.. and below is the error I get...

Is there another way of using this so it will work?

card.component.ts:

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

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css']
})
export class CardComponent{
  imageSrc : string;
  title : string;
  
  constructor(imgSrc : string, title : string) {
    this.imageSrc = imgSrc;
    this.title = title;
  }

  ngOnInit(): void {
  }

cards.service.ts:

import { CardComponent } from './card/card.component';

export class CardsService{
    ctgryCards : CardComponent[] = [
        new CardComponent("https://cdn3.iconfinder.com/data/icons/outline-amenities-icon-set/64/Beauty_Saloon-512.png", "Beauty"),
        new CardComponent("https://www.pinclipart.com/picdir/middle/391-3917890_get-business-value-from-sustainable-data-electronics-icon.png", "Electronics")
      ];

      getAllCtgryCards(){
          return this.ctgryCards.slice();
      }
}

home.component.ts:

import { Component, OnInit } from '@angular/core';
import { CardComponent } from '../card/card.component';
import { CardsService } from '../cards.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
  categoryCards : CardComponent[] = [];
  constructor(private cardsServ : CardsService) { }

  ngOnInit(): void {
    this.categoryCards = this.cardsServ.getAllCtgryCards();
  }
}

home.component.html:

<app-card *ngFor = "let card of categoryCards"></app-card>

Error NG2003:

ERROR in src/app/card/card.component.ts:12:15 - error NG2003: No suitable injection token for parameter 'imgSrc' of class 'CardComponent'. Found string

constructor(imgSrc : string, title : string) {

1 Answers

In card.component.ts:

Update the constructor to be

//import { Inject } from '@angular/core';

constructor(@Inject(String) private imgSrc : string, title : string)

OR

//import { Inject } from '@angular/core';

constructor(@Inject('imgSrc') private imgSrc : string, title : string)

According to https://angular-2-training-book.rangle.io/di/angular2/inject_and_injectable ; @Inject() is a manual mechanism for letting Angular know that a parameter must be injected. @Inject decorator is only needed for injecting primitives.

The primitive types are number, string, boolean, bigint, symbol, null, undefined.

Related