Home > Blockchain >  Add html element (or angular component) on call of a function, in angular
Add html element (or angular component) on call of a function, in angular

Time:01-20

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.

CodePudding user response:

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.

CodePudding user response:

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

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

CodePudding user response:

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

  •  Tags:  
  • Related