0

I have a component, that has a button. The button is connected to a function in the .ts file. Now, I want the function to add an HTML element or maybe un-hide it on the click of the button. I basically just want an html <div> element to become visible on the screen (with some dynamic data).

Following is what the button in the component.html file looks like:

<button mat-button (click)="getInfo()" mat- cdkFocusInitial>Ok</button>

Following is what the getInfo() function in the component.ts file currently looks like:

getInfo(){
    console.log("Button clicked");
}

So my objective is, on the click of the button, some element appears on the screen or maybe another angular component appears. Some advice on how to achieve that would be very helpful.

Thanks in advance!

PS: I am very new to front-end development, but I did try reading-up and searching on Stack-overflow and nothing comprehensive came up.

4
  • 1
    I think you can use *ngIf directive in .html and in .ts file create some boolean variable. After that in your method change this boolean variable to true - than element in html will appear. Commented Jan 19, 2022 at 20:19
  • So you want to add dynamically an html element/angular component or this will be hidden and you want to show it up? Commented Jan 19, 2022 at 20:21
  • @tufonas I actually want the element to be added dynamically, but if it's not possible, then I can work with un-hiding the element. Commented Jan 19, 2022 at 20:38
  • @MateuszŚcigała Thanks for the reply, I'll try that out! Commented Jan 19, 2022 at 20:39

3 Answers 3

1

You can do this by simply adding a boolean in your component.

showEl = false;

and on clicking button,

getinfo() {
   this.showEl = !this.showEl;
}

And in template, you can use *ngIf to show/hide the content.

Sign up to request clarification or add additional context in comments.

Comments

1
<button (click)="isShowInfo = !isShowInfo">Toggle me</button>

<div *ngIf="isShowInfo">
   <p>Here is my info</p>
</div>

Comments

0

You can use the hashtag of angular to make your code simpler.

<button (click)="testId.style.visibility = 'visible'">Unhide me</button>

<div style="visibility: hidden;" #testId>
   i am hidden
</div> 

If you want to unhide it from the typescript you have to use @ViewChild to watch the hidden element and when you call one method on click you will set the visibility to visible

2 Comments

avoid using "style" tag. avoid using "visibility: hidden". avoid using template-var. Use *ngIf as much as possible.
Agreed with @Random

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.