Kiran Cyrus Ken
Kiran Cyrus Ken

Reputation: 389

Angular: This type is not supported as injection token

I am just trying to create a constructor with type number but I am getting the error as 'This type is not supported as injection token'

I am new to Angular. What am I doing wrong here?

import { Component } from '@angular/core'

@Component({
    selector : 'app-even',
    templateUrl : './even.component.html',
    styleUrls : ['./even.component.css']
})
export class EvenComponent
{
    num : number;
    
    constructor(num : number){
        this.num = num;
    }
}

I am getting the below error:

Injection type error

I use this EvenComponent in AppComponent

export class AppComponent implements DoCheck{
  evenCounts : EvenComponent[];
}

Upvotes: 2

Views: 11452

Answers (2)

John Tiggernaught
John Tiggernaught

Reputation: 788

If you want to pass data to a component, you need to use @Input(). For example:

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

@Component({
    selector : 'app-even',
    templateUrl : './even.component.html',
    styleUrls : ['./even.component.css']
})
export class EvenComponent implements OnInit
{
    @Input() num : number;
    
    constructor() { }

    ngOnInit(): void {

        // You can use this value now
        console.log(this.num);

    }

}

To pass the value into the component, you add the following to the parent HTML template:

<app-even [num]="3"></app-even>

Note: You can't use the values passed into a component in the constructor because the value won't be ready yet and you'll always get undefined.

If you're new to Angular it might be worth going through the Tour of Heroes tutorial to pick up some core knowledge.

Good luck!

Upvotes: 4

Adith Sukumar
Adith Sukumar

Reputation: 92

Angular is trying to resolve the dependency of num. If you are trying to pass num to component, I suggest using @Input() decorator

https://angular.io/guide/inputs-outputs

https://angular.io/guide/dependency-injection

Upvotes: 0

Related Questions