Reputation: 654
I have a component in my app like this:
@Component({
selector: 'app-payment-intent',
templateUrl: './payment-intent.component.html',
styleUrls: ['./payment-intent.component.css']
})
export class PaymentIntentComponent implements OnInit {
static = false;
@ViewChild(StripeCardComponent, this.static) card: StripeCardComponent;
But, when i try to compile the app, i get
Object is possibly 'undefined'
The error is in the variable static = false
that is causing that @ViewChild(StripeCardComponent, this.static) card
is receiving the variable as possible undefined
, but as you can see the variable is not undefined
, the variable is a boolean initializated in false
..
What can i do to solve this problem?
Thank you!
Upvotes: 2
Views: 2115
Reputation: 538
@ViewChild, in this case, is a decorator. To understand the problem, you need to understand how decorators work and how they apply to methods.
Original code:
function decorator(value?:any) {
return function <T>(target: unknown, propertyKey: string, descriptor: TypedPropertyDescriptor<T>): void {
console.log('value:', value);
};
}
class Bar {
@decorator(this)
public foo():void {}
}
Compiled code:
// __decorate and __metadata declarations skipped
function decorator(value) {
return function (target, propertyKey, descriptor) {
console.log('value:', value);
};
}
class Bar {
foo() { }
}
__decorate([
decorator(this),
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], Bar.prototype, "foo", null);
After compiling this code, you can see that the decorators modify the prototype class, not its instance. Thus, "this" in the argument "this.static" you pass to the decorator points to no context, and therefore its value is undefined.
Upvotes: 4
Reputation: 8269
You can refer to the Angular's Static Query Migration where it shows that the @ViewChild
2nd parameter is { static: boolean }
type, so you should edit yours to:
@ViewChild(StripeCardComponent, { static: this.static }) card: StripeCardComponent;
or much better to assign it directly, since this condition will apply upon initialization:
@ViewChild(StripeCardComponent, { static: false }) card: StripeCardComponent;
Upvotes: 2