Passing Data to Stencil Component using @Prop()

Passing Data to Stencil Component using Prop

In this article, we are going to learn how to pass data to component using @Prop() property

Before going to read this article, you are recommended to read this article, if you didn’t read it.

Here is an example to pass data:

<br />import { Component,Prop } from '@stencil/core';<br /><br />@Component({<br />    tag: 'my-component'<br />})<br /><br />export class MyComponent {<br /><br />    @Prop() subject:string;<br /><br />    render() {<br />        return (&lt;p&gt;I am learning {this.subject}&lt;/p&gt;)<br />    }<br /><br />}<br />

Note that we import Prop from @stencil/core.

We can get value of the property using { }(curly braces), In our example we have used {this.subject}.
it will return subject value.

Here is how we can pass data from element

<br />&lt;my-component subject="stencil"&gt;&lt;/my-component&gt;

Any property decorated with @Props() is also automatically watched for changes. If a user of our component were to change the element’s name property, our component would fire it’s render function again, updating the displayed content.

Now when we run this project we will get the following output:

This way we can pass data to component.

Thanks for reading the article. 🙂

Leave a Comment