The Lightning Web Components programming model has three decorators that add functionality to a property or function.
In this blog we will learn the use of "@api decorator in Lightning Web Component".
1) @api decorator is used to expose a public property.
2) Public properties are reactive i.e If the value of a public property used in a template changes, the component rerenders and when a component rerenders, the expressions used in the template are reevaluated.
3) Import the @api decorator from lwc as shown below.
testComponent.js
import { LightningElement, api } from 'lwc';
export default class TodoItem extends LightningElement {
@api messageToDisplay= 'Test Message';
}
messageToDisplay is exposed as a public property in above example.
4) Parent component can make use of the Public Property.
5) A component that declares a public property can set only its default value.
6) A parent component that uses the child component in its markup can set the child component’s public property value.
Let us understand with an example,
apiDecCompTesting.html
<template>
<p>{messageToDisplay}</p>
</template>
apiDecCompTesting.js
import { LightningElement, api } from 'lwc';
export default class ApiDecCompTesting extends LightningElement {
@api messageToDisplay= 'Test Message';
}
parentApiDecComp.html
<template>
<div>
<p>
<b>Calling child comp</b>
<c-api-dec-comp-testing></c-api-dec-comp-testing>
</p>
</div>
<div>
<p>
<b>Calling child comp by passing value</b>
<c-api-dec-comp-testing message-to-display="From Parent"></c-api-dec-comp-testing>
</p>
</div>
</template>
parentApiDecComp.js
import { LightningElement } from 'lwc';
export default class ParentApiDecComp extends LightningElement {
}
TestLWCApp.app
<aura:application>
<c:parentApiDecComp></c:parentApiDecComp>
</aura:application>
Output:
Now let us understand the impact by removing @api decorator from the above example.
apiDecCompTesting.html
<template>
<p>{messageToDisplay}</p>
</template>
apiDecCompTesting.js
import { LightningElement} from 'lwc';
export default class ApiDecCompTesting extends LightningElement {
messageToDisplay= 'Test Message';
}
parentApiDecComp.html
<template>
<div>
<p>
<b>Calling child comp</b>
<c-api-dec-comp-testing></c-api-dec-comp-testing>
</p>
</div>
<div>
<p>
<b>Calling child comp by passing value</b>
<c-api-dec-comp-testing message-to-display="From Parent"></c-api-dec-comp-testing>
</p>
</div>
</template>
parentApiDecComp.js
import { LightningElement } from 'lwc';
export default class ParentApiDecComp extends LightningElement {
}
TestLWCApp.app
<aura:application>
<c:parentApiDecComp></c:parentApiDecComp>
</aura:application>
Output:
No comments:
Post a Comment