rocks6
rocks6

Reputation: 172

Cannot create constructor for angular component with a string as param

I have a simple component:

export class PlaintextComponent implements OnInit {
  schema: PlaintextTagSchema;

  constructor(private _ngZone: NgZone, prompt: string, maxRows: number, maxChars: number) {
    this.schema.prompt = prompt;
    this.schema.maxRows = maxRows;
    this.schema.maxChars = maxChars;
  }

  ngOnInit() {
  }
}

When I try to compile my app using ng serve, I get the error:

component.ts:25:40 - error NG2003: No suitable injection token for parameter 'prompt' of class 'PlaintextComponent'.
Found string

25   constructor(private _ngZone: NgZone, prompt: string, maxRows: number, maxChars: number) {

I've looked all over on the internet for this cryptic error and haven't found anything resembling a fix. It looks like a correct constructor to me, but I'm new to angular/TS and it's highly possible i'm missing something incredibly basic. Thanks in advance for the help.

Upvotes: 5

Views: 1988

Answers (2)

I had the same error. Looks like Angular is trying to do some dependecies injection with the parameters in the constructor (like the ones you do with services), but in your case, this will lead to errors. Just declare your class properties out of the parameters of the constructor. Move your class properties out of the constructor like this:

export class PlaintextComponent implements OnInit {
  schema: PlaintextTagSchema;
  private _ngZone: NgZone;
  prompt: string;
  maxRows: number; 
  maxChars: number;

  constructor() {}

  ngOnInit() {
  }
}

You maybe have to find another way to initialize your Component, like input properties.

Please, let me know if it works! ;D

Upvotes: 1

Useme Alehosaini
Useme Alehosaini

Reputation: 3116

Rewrite the Constructor as following

  constructor(private _ngZone: NgZone, @Inject(String) prompt: string, maxRows: number, maxChars: number)

dont forget

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

Upvotes: 2

Related Questions