I call jquery fun in my blazor app. I'm doing some services in Onin - I would like to call this function in my razor component. I did use the following code in the component. The function is showing when the page has loaded. But when I doing any clicking or changing any value in the page, even like a change a text that not related to the function, the function existed every time. Any hint?
protected override void OnAfterRender(bool firstRender)
{
if(!firstRender)
{
await JsRuntime.InvokeVoidAsync("TextArea.AddLineToTextArea");
}
You may wonder why I put (!firstRender), the reason is that by default the firstRender is false, and I don't know the reason. Some people say ,According to this Blazor Component Reference Null on First Render, that if your component in if/else it will cause the issue. but mine is out side
here is my function is adding a linenumber to textarea.
window.TextArea = {
AddLineToTextArea:function(){
$(".lined").linedtextarea(
{selectedLine: 1}
);
// Target a single one
$("#inpDefinition").linedtextarea();
}
}
If you reverse the if condition you should have what you need:
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeVoidAsync("TextArea.AddLineToTextArea");
}
}
This code means that the await JsRuntime.InvokeVoidAsync("TextArea.AddLineToTextArea");
statement will be executed only once, when the component has it first rendering.
The method OnAfterRender
is executed everytime the component is updated, for example a user click on a button or whatever. But the boolean parameter firstRender
is equal to true for the first rendering, and will be false after.