I am attempting to print out the recordId of an account, using a variable inside a lightning web component. Here is my code so far:
javascript:
import { LightningElement,api } from 'lwc';
export default class HelloWordAccount extends LightningElement {
@api recordId; //returns record id
message = this.recordId; //returns undefined?
}
html:
<template>
<ouput>{recordId}</ouput>
<br/> <br/>
<ouput>{message}</ouput>
</template>
The component is on the account page layout, and prints out the recordid inside of the output tags that reference "recordId". I want to pass the recordId to a variable ("message"), when I pass it to a variable, I get nothing. putting the value in an input tag prints out "undefined". What am I doing wrong?
Best Answer
There are 3 things to be remembered here:
recordId
will be loaded after the class has been initialised and the framework knows the record context and so whenmessage = this.recordId;
is executed,recordId
will be undefined .connectedCallback()
method is invoked and so you should use this method .Below code will work: