Reputation: 553
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?
Upvotes: 1
Views: 1752
Reputation: 7446
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.
Upvotes: 3