1
votes

In Angular ViewChild Documentation , it is mentioned that:

The following selectors are supported:

Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)

In which use-case, child component provider need to be selector in ViewChild in parent component? I am not able to think of use-case of this functionality provided. I am not able search it over internet as well.

Angular University Blog about ViewChild Decorator also has no mention of this.

1
There's way too many applications of ViewChild to think of them all. Some angular features stay untouched in projects forever, but that doesn't mean that only because you never have to use them, that they are entirely useless.Mike S.
I agree with you. Bht there must be some use-case that is why angular provides this functionality. What is it?Kavar Rushikesh

1 Answers

0
votes

ViewChild makes it possible to access a child component and call methods or access instance variables that are available to the child.

Let’s say we have a ChildComponent. Ideally, you will use @angular/cli to generate your component:

ng generate component child --flat

Otherwise, you may need to create child.component.css and child.component.html files and manually add it to app.module.ts:

app.module.ts
import { ChildComponent } from './child.component';
...
@NgModule({
  declarations: [
    AppComponent,
    ChildComponent
  ],
  ...
})

We will add a whoAmI method to ChildComponent which returns a message:

child.component.ts

whoAmI() {
  return 'I am a child component!';
}

Next, we will reference the component in our app template:

app.component.html <app-child>child works!</app-child>

Now, we can call the whoAmI method from within our parent component class with ViewChild like this:

app.component.ts
import {
  Component,
  ViewChild,
  AfterViewInit
} from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  @ViewChild(ChildComponent) child: ChildComponent;
  ngAfterViewInit() {
    console.log(this.child.whoAmI()); // I am a child component!
  }
}

When viewing the application in a browser, the console log will display:

Output

I am a child component!

The parent component was able to call the child component’s whoAmI method.