3
votes

There are many code examples that demonstrate component communication,

I am confused about what is the difference between that two techniques

  • ChildComponent
  • ViewChild

ViewChild is defined:

ViewChild decorator get access to a child component, directive or a DOM element from a parent component class, ViewChild returns the first element that matches a given component, directive or template reference selector.

According to this reference,

The ViewChild give full access to the parent component to the DOM elements, directive without to send EventEmitter to the parent component on any updates.

my questions

  • we can say the relation between parent component and viewchild is only one-way biding, and between parent component and child component is 2-way binding?
  • How the act under the core, data Binding, Lifecycle?

  • What are the real practical usages, and which problem it comes to solve?

2

2 Answers

4
votes

Yes, some of this terminology is confusing.

In most cases, a parent and child relationship (parent component and child component) are referring to a component within the HTML of another component.

In the below example, the "star" component is a child component within the product detail component.

enter image description here

The child component is literally added within the parent component's template:

Parent template:

  <div class='col-md-8'>
    <pm-star [rating]='product.starRating'>
    </pm-star>
  </div>

Child component

@Component({
  selector: 'pm-star',
  templateUrl: './star.component.html',
  styleUrls: ['./star.component.css']
})
export class StarComponent {
  // ...
}

The ViewChild decorator on the other hand allows you to get access to any element on the component's associated template. You can then access it directly. This is not directly related to parent/child components.

For example, you could get access to any random <div> element on a page and set its background color. Or you could get access to an <input> element and set its focus.

Hope this helps to clarify the difference.

0
votes

Component interactions is the way two components are communicating with each other.

ViewChild decorator is one of the existing component interactions.