Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ViewChild in Angular2?

From the official documentation. A ViewChild:

Configures a view query.

View queries are set before the ngAfterViewInit callback is called.

The explanation is very minimal and I still don't quite understand what is it used for.

Consider this example from a blog I found.

Taking away the @ViewChild(TodoInputCmp) have no effect on the code inside TodoInputCmp

Can someone give me some insight?

Thanks

like image 455
testing Avatar asked Apr 14 '16 05:04

testing


People also ask

What is ViewChild ()?

ViewChildlinkProperty decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

What does ViewChild return?

The ViewChild decorator returns the first element that matches a given directive, component, or template reference selector.

Why do we need ViewChild and ViewChildren in Angular?

Both ViewChild and ViewChildren are used to communicate between the components to access the data. @ViewChild and @ViewChildren are the types of decorators used to access the child component class and its different properties into the parent component. It's similar to the inheritance.

How do I use ViewChild with ElementRef?

In a parent component we can use @ViewChild() for components, directives. The @ViewChild() can be also be used for template reference variable with ElementRef or TemplateRef . To use @ViewChild() we need to pass child component name or directive name or template variable as an argument.


2 Answers

It provides a reference to elements or components in your view:

@Component({
  ...
  directives: [SomeComponent],
  template: `
  <div><span #myVar>xxx</span><div>
  <some-comp></some-comp>`
})
class MyComponent {
  @ViewChild('myVar') myVar:ElementRef;
  @ViewChild(SomeComponent) someComponent:SomeComponent;
  
  ngAfterViewInit() {
    console.log(this.myVar.nativeElement.innerHTML);
    console.log(this.someComponent);
  }
}

IMPORTANT: The variables are not initialized before ngAfterViewInit()

like image 169
Günter Zöchbauer Avatar answered Oct 12 '22 01:10

Günter Zöchbauer


The ViewChild decorator is used to gain access to a child component, found in the template, so that you can access its properties and methods.

like image 14
rgvassar Avatar answered Oct 12 '22 02:10

rgvassar