Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Nested Components Works in Stencil?

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>
    );
  }
}
like image 836
Abhishek Gangwar Avatar asked Nov 07 '25 20:11

Abhishek Gangwar


1 Answers

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.

like image 136
Sébastien Avatar answered Nov 09 '25 10:11

Sébastien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!