4

I found These Snippets in Stencil's Official Docs.

I am not able to understand how my-embedded-component is accessible in my-parent-component without providing the path of child component. Can anyone help me understand this concept?

Child Component

import { Component, Prop } from '@stencil/core';

@Component({
  tag: 'my-embedded-component'
})
export class MyEmbeddedComponent {
  @Prop() color: string = 'blue';

  render() {
    return (
    <div>My favorite color is {this.color}</div>
    );
  }
}

Parent Component

import { Component } from '@stencil/core';

@Component({
  tag: 'my-parent-component'
})
export class MyParentComponent {

  render() {
    return (
      <div>
        <my-embedded-component color="red"></my-embedded-component>
      </div>
    );
  }
}
Milad
  • 27,506
  • 11
  • 76
  • 85
Abhishek Gangwar
  • 2,168
  • 18
  • 26

1 Answers1

2

There is no path. The relationship is created because the elements are nested in the HTML source.

In plain HTML the following structure, a paragraph inside a div, creates a parent/child relationship in the DOM:

<div>
    <p>Hello World!</p>
</div>

You are doing the same thing by using my-embedded-component inside the template of MyParentComponent. Before the parent component is rendered on the page, the initial HTML source is something like:

<my-parent-component>
    <div>
        <my-embedded-component color="red"></my-embedded-component>
    </div>
</my-parent-component>

This is then compiled to apply the behaviors described in the respective components.

The tag property in the @Component decorator defines the name of the custom tag you use in the HTML.

When the Angular compiler reads your initial HTML source code it looks for directives (tags, attributes, etc.) that have to be transformed. When those directives are nested, it creates in implicit relationship: the parent may use some of the children's properties or vice-versa.

Sébastien
  • 11,860
  • 11
  • 58
  • 78