Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use document.querySelector in TypeScript/ Angular?

I’m trying to write a login/register form where the user can toggle between the two forms (only one is shown at a time). I use a simple button to perceive the changes.
I’ve written it in a simple html file an it works. Now I’ve copied to my Angular project and nothing happens.

First I tried this one (it’s in the html file):

<script>
  function showlogin() {
    document.querySelector('#login').classList.remove("d-none");
    document.querySelector('#register').classList.add("d-none");
  }


  function showregister() {
    document.querySelector('#login').classList.add("d-none");
    document.querySelector('#register').classList.remove("d-none");
  }


</script>

But then I got an error that says that "Property ‘showregister’ does not exist".
So I remove the code from the html file and paste it in the typescript file.
Now I get an new error "Object is possibly ‘null’."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why is the Object null? What can I do to have access to the button and the function?

I’m very thankful for any help

>Solution :

Use the Angular way!

Code Behind:

loginVisible: boolean = true;
...
function showLogin() {
    loginVisible = true;
}

function showRegister() {
    loginVisible = false;
}

And the html part:

<div *ngIf="loginVisible">Login Data</div>

<div *ngIf="!loginVisible">Register Data</div>

Here is a simple Stackblitz example.

The ngIf will only render the component if the condition is true.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading