3

I have below code working before Angular 10 upgrade ie., Angular 8.

@viewChild in @injectable was working in Angular8 but not in Angular10 any reason ?

Code below is the sample (below is how my existing code looks):

@Injectable()
export abstract class DetailBaseComponent
  extends BaseComponent {

/**
   * Reference to the child modal component
   */
  @ViewChild(ModalComponent)
  modal: ModalComponent;

findDetail(){
  console.log(this.modal); //undefined
  this.modal.showModal = true;// error
}

But when i moved @viewChild from @Injectable to a component class then it was working fine. Is there any reason that we cannot use @viewChild except in component class then ??

Help Appreciated!

JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
Pradeep
  • 1,192
  • 2
  • 12
  • 30
  • According to the [docs](https://angular.io/api/core/ViewChild), `@ViewChild()` cannot be used together with `@Injectable()` – JSON Derulo Dec 17 '20 at 16:42
  • But it was working before. I was using Angular8 – Pradeep Dec 17 '20 at 16:50
  • Now we upgraded to Angular 10 then it is not working – Pradeep Dec 17 '20 at 16:50
  • Doesn't matter if it worked before. This has never been officially supported, just checked the [v8 docs](https://v8.angular.io/api/core/ViewChild). So I guess you need to find another approach. – JSON Derulo Dec 17 '20 at 16:51
  • Also in my opinion it makes no sense. By design, an Injectable cannot have a template. Why should it then have a ViewChild? – JSON Derulo Dec 17 '20 at 17:01
  • @JSONDerulo Thanks for pointing things – Pradeep Dec 17 '20 at 18:29
  • Any injectable should be able to reference the application html which is the context for it. It's useful for injecting divs into root template, get viewchild references. Now we have to do stuff like that in the root application component, making separation of concern horrible – Spock Jul 06 '23 at 08:02

1 Answers1

0

Replace @Injectable() with @Directive()

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 4
    Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Jul 06 '22 at 10:20