Home > front end >  I want to helights my div using loop in angular
I want to helights my div using loop in angular

Time:09-22

Better understanding for I mentioned the Images.

If i am not selecting anything of div Property, the default style(css) should be Like this , alteast selected one div. but here, problem is unable to selected.

this is my component :

<div *ngFor="let item of data; let i = index;" (click)="setRow(i)" 
    [ngClass]="{'highlight': selectedIndex===i}" 
>
    {{item}}
</div> 

css :

.cycleHover{
    cursor: pointer;
    padding: 5px 20px;
    margin: 4px;
    font-style: normal;
    font-weight: 700;
    font-size: 14px;
    // line-height: 18px;

    color: #010103;
}

.highlight{ 
    background-color: #fff;
    padding: 5px 20px;
    margin: 4px;
    color: #737D88;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.05);
    border-radius: 24px;
}

ts:

selectedIndex: any;

data: any[] = ["D", "W", "M", "Q", "Y"];

 setRow(_index: number) {
    this.selectedIndex = _index;
  }

CodePudding user response:

As a side note, you can make clearer, more concise code like this :

<div *ngFor="let item of data" 
    (click)="selected = data" 
    [class.highlight]="selected === data"
    
>
    {{item}}
</div> 
data = ["D", "W", "M", "Q", "Y"];
selected = this.data[0]; // Or undefined depending on what you want

CodePudding user response:

if you want to select first as a default then change declaration of selectedIndex in your ts file like this:

selectedIndex:number=0;

CodePudding user response:

if you want to select middle as a default then put this code in ngOnInit(){}

this.setRow(Math.floor(this.data.length/2));
  • Related