简体   繁体   中英

How to access super-class property in sub-class component template? Angular

I have an abstract super class that defines a property "proposal".

export abstract class myBaseClass {
  public proposal: Proposal;
}

and a class that extends it

export class mySubClassComponent Component extends myBaseClass{
    constructor() {
      super();
  }
}

I try to access the property "proposal" of myBaseClass in the template of mySubClassComponent like this:

*ngIf="proposal.position"

but I'm getting the following error

TypeError: Cannot read property 'position' of undefined

how can I have access to this property inside the mySubClassComponent tempalte?

You are accessing it correctly. However, you have defined the type but, in fact, the class property is actually undefined .

Just add a null check in your ngIf and you will be done:

*ngIf="proposal?.position"

This will avoid undesired errors if proposal is declared but its value is undefined .

Basically, to make it clearer, this:

export abstract class myBaseClass {
  public proposal: Proposal;
}

is the same as this:

export abstract class myBaseClass {
  public proposal: Proposal = undefined;
}

Keep in mind that, in typescript, declaring a variable type have no effects after the code is compiled. If a variable is undefined, it will be undefined at runtime, regardless the type you have declared in your typescript code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM