简体   繁体   中英

What is ViewChild

There is declaration in component:

export class GlossariesComponent implements OnInit {
  @ViewChild(UploaderComponent, {static: false})
  private uploader: UploaderComponent;

}

Does it mean that I do reference to TEMPLATE of UploaderComponent component?

How then to use @ViewChild in current component template, now there is no place where it is used in template.

And what does mean static?

Does it mean that I do reference to TEMPLATE of UploaderComponent component?

Not quite, you will get the instance of that component's class.

How then to use @ViewChild in current component template, now there is no place where it is used in template.

The purpose of @ViewChild is to query elements from your current component's view (template).

You can use a component in 2 ways:

  • declaratively : by using its selector in a view
  • imperatively : in simple terms, everything is done inside your class. now it is important to know about embedded views and host views (these are the components loaded imperatively)

These views must be hosted by a view container, which its job is, as its name implies, to contain multiple views.

Read more here about host views, embedded views and view container .

If you have not used the component in your template, then you shouldn't be able to grab it in your class.

And what does mean static?

when:

  • true
    • it is accessible in ngOnInit()
    • does not depend on any of *ngIf , *ngFor
  • false
    • depends on a binding resolution( *ngIf etc...)
    • accessible in ngAfterViewInit and ngAfterViewChecked

You can find more details here .

EDIT

why it is named as @ViewChild no @ViewCurrent

Here is my assumption:

<app-root>
  <#VIEW>
    <app-child>
     <#VIEW>
       ...content goes here...
     </#VIEW>
    </app-child>
  <#VIEW>
</app-root>

Snippet taken from here

Now, imagine you want to query for app-child

root.component.ts

@Component({ /* ... */ })
export class RootComponent {
 @ViewChild(AppChild, { static: false })
 private appChild: AppChild;
}

A TLDR would be: every element(DOM element or component) in a component's view is technically a child of that component.

When you Want to get access to a child component, directive or a DOM element from a parent component class, It's easy to do with the ViewChild decorator. ViewChild returns the first element that matches a given component, directive or template reference selector. In cases where you'd want to access multiple children, you'd use ViewChildren instead. Check this for detailed explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM