Nikola Yankov
Nikola Yankov

Reputation: 1304

Angular 2: Property injection instead of constructor injection

Can I do this:

export class BaseComponent {
protected config: IConfig;

@Inject(AppConfig) protected appConfig: AppConfig;

constructor() 
{ 
    this.config = this.appConfig.getConfig();    
}

instead of this:

export class BaseComponent {
config: IConfig;

constructor(
    private appConfig: AppConfig,
    ) 
{ 
    this.config = appConfig.getConfig();    
}

The goal is to simplify the constructor signature, so all child component to not need to specify appConfig in their constructor. So the components that inherits from BaseComponent to look like this:

@Component({
    selector: 'sport-templates',
    templateUrl: 'templates.component.html',
    styleUrls: [ 'templates.component.scss' ],
    encapsulation: ViewEncapsulation.None
})
export class SportTemplates extends BaseComponent implements OnInit {

    constructor() {
        super();
    }

instead like this:

@Component({
    selector: 'sport-templates',
    templateUrl: 'templates.component.html',
    styleUrls: [ 'templates.component.scss' ],
    encapsulation: ViewEncapsulation.None
})
export class SportTemplates extends BaseComponent implements OnInit {

    constructor(appConfig: AppConfig) {
        super(appConfig);
     }

Upvotes: 17

Views: 7392

Answers (3)

kvetis
kvetis

Reputation: 7341

This is now (since Angular v14) possible to do via the inject function from @angular/core. It behaves the same as the decorator and can be used on property initializers:

@Directive()
export abstract class BaseComponent {
    protected appConfig = inject(AppConfig)
}

Therefore, you don't need to call super(appConfig) any more.

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68665

No you can't do it. Injectable service will e injected when the constructor is called.

The goal is to simplify the constructor signature.

There is no need to simplify constructor signature. For readability you can write them in multiple lines.

so all child component to not need to specify appConfig in their constructor

In your case only classes that inherit your class will access that. But if you mean child component those ones which are used in your component, they can't access variables in parent component. You need to pass them.

UPDATED

Your this.config is always visible in inherited components. There is no need to again inject appConfig in the SportTemplates component.

Upvotes: 0

Mikael Kristensen
Mikael Kristensen

Reputation: 260

You can do this:

myService: MyService = this.injector.get(MyService);
constructor(private injector:Injector) {}

The Injector is in @angular/core

Upvotes: 3

Related Questions