After adding a string parameter to the constructor in my class I am getting an error in the browser:
My class is defined as follow:
import { Component, OnInit } from '@angular/core';
import { MatrixComponent } from '../matrix/matrix.component';
@Component({
selector: 'app-player',
templateUrl: './player.component.html',
styleUrls: ['./player.component.css']
})
export class PlayerComponent implements OnInit {
private userName: string;
constructor(private name: string) {
this.userName = name;
this.discovered = 0;
this.matrix = new MatrixComponent();
}
ngOnInit() {
}
}
And I am creating the object in the constructor of another class:
var player1 = new PlayerComponent("Me");
I think it is possible to pass parameters in the constructor right? What's wrong with my code?
As explained in this question,
the @Component
decorator tells angular
that it is a not a normal typescript class
, but an Angular Component
.
Thus, to make it work, you would have to tell it that string
is a provider
for your component, as it expects the constructor parameter to be a provider (which is either declared in the component's metadata
or in the module).
string
wouldn't work as it's not a known angular 2 provider (unless you create a service with name string
).
This explains why we can create these kind of constructors (string
as arguments) in normal classes but are not allowed in angular components.
I hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With