Search code examples
angulartypescripthyperlinkangular-ng-if

How to show the data when we click on the link in angular


I have an angular application In this I I have one link i.e show data and when we click on the show the the data and the link has to be changed to hide data from show data .

and when we click on the hide data the data has to be hidden and the link needs to be changed to show data.

.component.html

<a >show data</a>
<a>hide data</a>
<div>
//here needs to show the data
</div>

Can anyone help me on the same


Solution

  • If I'm reading your question right, it sounds like you want a click event to display some data. There are a couple of ways to do this. Here is one example:

    In the html, you will add a click event handler to the anchor tag which will call the function toggleData(). Then, in the typescript function, you can set the property called "dataShown" to the opposite of its current value. In your html, you can use the *ngIf directive to show data if dataShown is true or not if false. The *ngFor directive can be used to loop through a list of data items if you like. To change the text of your link, there is string interpolation in the {{ }} and inside the curly braces, we can use a ternary operator to check if dataShown is true or false. The "Hide" text right after the ? is to indicate what should happen if dataShown is true, the "Show" text is what should happen if dataShown is false.

    your.component.html:
    <a (click)="toggleData()">{{ dataShown ? "Hide" : "Show" }} Data</a>
    <div *ngIf="dataShown">
        <div *ngFor="let dataItem of dataList">
            {{ dataItem.title }}
        </div>
    </div>
    
    your.component.ts (in the 'export class' section):
    dataList: dataItem[]; // This assumes you have a dataItem class or interface with a title property
    dataShown: boolean = false; // Data not shown by default, could be true if desired.
    toggleData() : void {
        this.dataShown = !this.dataShown;
    }
    

    I hope this help!