Malindu Sandaruwan
Malindu Sandaruwan

Reputation: 1517

Angular sub class template accessing a variable defined in a super class

My super class component has a variable say name. (a protected variable)

I want to access it in a sub class html like {{name}}. But it gives following error on production build.

Property 'name' is protected and only accessible within class 'ABCSuperComponent' and its subclasses

When I make the name variable public it works fine. But it's not a good OOP practice. So any solutions/advices or suggestions on my problem?

Upvotes: 2

Views: 2209

Answers (4)

Rofls
Rofls

Reputation: 169

50 reputation to be able to comment????

I've noticed that in some instances AOT allows access to protected properties and methods.

for example

when foo is protected then

<input [required]="foo"> will not cause an error during aot build

but

<p>{{foo}}</p> will cause an error

Upvotes: 0

Reactgular
Reactgular

Reputation: 54781

You can just make the property public and not worry about it.

export abstract MyClass {
      public name: string;
}

You can define public read access with protected write access.

export abstract MyClass {
      private _name: string;

      public get name(): string {
          return _name;
      }

      protected set name(value:string) {
          this._name = value;
      }
}

You can define a read access method

export abstract MyClass {
      protected name: string;

      public getName(): string {
           return this.name;
      }
}

Upvotes: 1

David
David

Reputation: 34445

When building for production, angular uses AOT. With this type of build, all variables/methods used in a template must be declared as public in the template's component.

From (https://github.com/angular/angular/issues/11978)

With JiT we convert all the code to ES5 and then in runtime we do the bindings. All the visibility modifiers are lost in that process, so it doesn't matter if you say public or private for that.

On the other hand, with AoT, we generate some typescript code for our templates, that will try to access those fields. If they are private, they simply cannot access those properties, hence, we have to put them as public.

This does not change anything that you are using the class in a child class, you'll have the same problem with any component which uses non public property in its template

Upvotes: 1

Amit Chigadani
Amit Chigadani

Reputation: 29715

If you are accessing any property inside your template, then it has to be declared as public. Or else it fails during production i. e ng build --prod. This may work fine during development.

ng build --prod does aot compilation. So it should be AOT compatible

Upvotes: 1

Related Questions