Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

June 15, 2017

Property ‘x’ is private and only accessible within class ‘MyComponent’

Filed under: Angular @ 6:13 pm

 

The content of this post is based on Angular version >= 2.x unless explicitly stated otherwise.

As with any application framework, there are those issues that trip up many developers. Some of these are due to changes to the framework over time, others are just unexpected results from seemingly correct code. I’ve tried to capture some of the more common issues and their solutions and here is one of them.

Property ‘x’ is private and only accessible within class ‘MyComponent’.

This issue began with Angular 4 and the release of the CLI. The Angular CLI enables the Ahead of Time (AOT) compiler when you use the `ng build –prod` option. The Ahead of Time compiler compiles things a bit differently, hence the reason this issue only appears with AOT.

Original sample code:

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

@Component({
    selector: 'mh-root',
    template: `
        {{pageTitle}}
        <router-outlet></router-outlet>
     `
})
export class AppComponent {
    private pageTitle: string = 'InStep Movie Hunter';
}

Error: Property ‘pageTitle’ is private and only accessible within class ‘AppComponent’.

Issue: With AOT, private properties and methods in the class are only accessible within the class. To access the property or method in the template, the property or method must be declared public.

Updated sample code:

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

@Component({
    selector: 'mh-root',
    template: `
        {{pageTitle}}
        <router-outlet></router-outlet>
     `
})
export class AppComponent {
    public pageTitle: string = 'InStep Movie Hunter';
}

For more information: https://github.com/angular/angular-cli/issues/5623

Enjoy!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2017 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs