Home > Blockchain >  "See more" button for text inside multiple cards built with *ngFor
"See more" button for text inside multiple cards built with *ngFor

Time:03-19

I'm generating multiple cards using *ngFor and I added see more button to overflow the text inside the card

Component.html

<div *ngFor="let classifciation of tenderClassification">
                        <mat-card >
                            <mat-card-title>{{classifciation.name}} </mat-card-title>
                            <mat-card-subtitle>Starting price {{classifciation.amount}} TND</mat-card-subtitle>


                            <mat-card-actions>


                               <p [ngClass]="{'limitTextHeight': isReadMore}">
                                 {{classifciation.description}} 
                            </p>
                            <button mat-button  (click)="showText()">
                                {{ isReadMore ? 'Read More': 'Read Less' }}
                              </button>
                              
                            
                            </mat-card-actions>
                        </mat-card>
                    </div>

Component.ts

  isReadMore = true;

  showText() {
     this.isReadMore = !this.isReadMore
  }

Component.css

.limitTextHeight {
height: 20px;
overflow: hidden;

}

And the result when I click to read more button all cards call the showText() function and all cards apply the read more but I want only that specific card to be applied with read more

Before I click enter image description here

After I click on one read more button enter image description here

Any solution to target that specific card?

CodePudding user response:

Create a new component that receives a classification as input.

card.component.html


<mat-card>
    <mat-card-title>{{classifciation.name}} </mat-card-title>
    <mat-card-subtitle>Starting price {{classifciation.amount}} TND</mat-card-subtitle>


    <mat-card-actions>


      <p [ngClass]="{'limitTextHeight': isReadMore}">
        {{classifciation.description}} 
    </p>
    <button mat-button  (click)="showText()">
        {{ isReadMore ? 'Read More': 'Read Less' }}
      </button>
      
    
    </mat-card-actions>
  </mat-card>
@Component({
  selector: 'app-card',
  template: `./card.component.html`,
})
export class CardComponent  {
  @Input() classification: any;

  isReadMore = true;

  showText() {
    this.isReadMore = !this.isReadMore
  }
}

in your parent component.

<div *ngFor="let classification of tenderClassification">
  <app-card [classification]="classification"></app-card>
</div>

As you can see the code is cleaner, and you can add more behaviour to each card component.

  • Related