4

@ViewChild and @ViewChildren query the elements from view DOM and @ContentChild and @ContentChildren query the elements from content DOM.

@ViewChildren(WriterComponent) 
writers: QueryList<WriterComponent>;    

@ContentChildren(WriterComponent) 
writers: QueryList<WriterComponent>

here I can't understand what exactly the difference between view DOM and content DOM, Could some one please explain it ?

3 Answers3

6

Let us say we have a component called my-component.

The @ViewChild and @ViewChildren will grab something inside that components template, so an html element that is inside the my-component.component.html file.

@ContentChild and @ContentChildren will grab something that is between the brackets of a parent component using the my-component. So let us say we have the following in our parent.component.html:

<my-component>
    <div class="name">Hans</div>
</my-component>

You can use @ContentChild and @ContentChildren to grab the "Hans" element.

SnorreDan
  • 2,740
  • 1
  • 14
  • 17
1

The children element which are located inside of its template of a component are called view children. On the other hand, elements which are used between the opening and closing tags of the host element of a given component are called content children.

Accessing View Children : View Child Docs

import {ViewChild, ViewChildren, Component, AfterViewInit...} from '@angular/core';

// ...

@Component({
  selector: 'todo-app',
  template: `...`
})
class TodoAppComponent implements AfterViewInit {
  @ViewChild(TodoInputComponent) inputComponent: TodoInputComponent
  @ViewChildren(TodoComponent) todoComponents: QueryList<TodoComponent>;

  constructor(private todos: TodoList) {}
  ngAfterViewInit() {
    // available here
  }
}

Accessing Content Children : Content Children Docs

@Component({
  selector: 'app-footer',
  template: '<ng-content></ng-content>'
})
class FooterComponent {}

@Component(...)
class TodoAppComponent {...}

@Component({
  selector: 'demo-app',
  styles: [
    'todo-app { margin-top: 20px; margin-left: 20px; }'
  ],
  template: `
    <content>
      <todo-app>
        <app-footer>
          <small>Yet another todo app!</small>
        </app-footer>
      </todo-app>
    </content>
  `
})
export class AppComponent {}


// ... in TodoAppComponent
    @Component(...)
    class TodoAppComponent implements AfterContentInit {
      @ContentChild(FooterComponent) footer: FooterComponent;
      ngAfterContentInit() {
        // this.footer now points to the instance of `FooterComponent`
      }
    }
    // ...
Abhishek Kumar
  • 2,501
  • 10
  • 25
1

The content DOM defines the innerHTML of directive elements . Conversely, the view DOM is a component’s template (component.html) excluding any template HTML nested within a directive