1

I have an Angular project and I'm trying to define a variable with the following type:

navbarLinks: QueryList<ElementRef>;

but I get the following error:

Property 'navbarLinks' has no initializer and is not definitely assigned in the constructor.

30   navbarLinks: QueryList<ElementRef>;

Now, I don't want to use this as a solution:

navbarLinks!: QueryList<ElementRef>;

Is there any other way I can fix this?

1
  • 1
    Either you initialize navbarLinks in the constructor, then you can just use your original code. Or you initialize it directly (i.e. not within a subscribe or then callback) in ngOnInit. That's what !: is for. Or you initialize it somewhere else, then it may be undefined so you use navbarLinks?: QueryList<ElementRef>; and handle the undefined case. Commented Dec 18, 2021 at 11:37

1 Answer 1

3

If you really do not want to set a default value to this property you need to adjust your type to

navbarLinks?: QueryList<ElementRef>;

which is the same as

navbarLinks: QueryList<ElementRef> | undefined;

Another solution would be to give the property a default value. As I don't know what the QueryList<T> interface looks like, I can't really give you an example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.