Execute a method on an HTML element without using the click event

Asked

Viewed 55 times

0

Good evening, I have a radio button in a form, where it is only called when it meets the condition of a *ngIf, however, when ngIf is accepted and this element is called, I need a method to be executed, without having to click any button. Follow my code snippets:

<mat-radio-button name="G01" *ngIf="getClass0()" class="margem" value=0 checked>0</mat-radio-button>

    Desabilitar(element){
var radio = document.getElementById(element) as HTMLInputElement;
if(radio.style.display == 'none'){
  radio.style.display = 'table-cell';
}else radio.style.display = 'none';

}

I need this method to be called, as soon as this radio button appears on the screen.

1 answer

0

You should not use window.onload, because some elements can be loaded asynchronously and then in these cases may not yet be found.

For a greater guarantee use:

If you’re used to jquery:

$(document).ready(function(){
  Desabilitar(...)
});

If you want something without dependency, use:

document.addEventListener('DOMContentLoaded', function() {
   Desabilitar(...)
}, false);

Know that it is almost certain that the above examples will work, but still may not work in some browsers, so this example below is guaranteed in any browser:

setTimeout(function(){
  Desabilitar(...)
}, 3000);

I hope I’ve helped.

  • Actually, I don’t want to perform the function as soon as the page loads, but rather when the radio button is loaded. It is not loaded as soon as the page is opened, it has a *ngIf, and is only loaded when the condition of it is satisfied

  • I’m sorry, I hadn’t read it properly. do not know how to help you, but a not very trivial way would be to encapsulate the component in a directive, and this directive check with setTimeout(fnc, time) if the component already exists and execute what you want ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.