0

I have a for loop that print the content of an array. I would like one line to be highlighted.

The array is stored in my component.ts, as well as the line to highlight (but to simplify i'll fix it at 1)

I know this works:

<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<body ng-app="">

<div ng-style="{color: (1==1)?'aqua':'black'}">Sample Text</div>

</body>

And this print my array content in black properly

<div *ngFor="let i of this.getCode()">  {{i}} <br></div>

But when i try to have both it throws at runtime : Cannot find a differ supporting object

<div *ngFor="let i of this.getCode()" ngStyle="{color: (i==1) ? 'aqua' : 'black'}">  {{i}} <br></div>

enter image description here

5
  • I think this error is thrown, when your data, here this.getCode(), does not is an array. Please try to log it to the console and prove that it is an array. Commented May 13, 2021 at 11:18
  • 1
    if you are calling any method in your html then no need to write this you can direclty call getCode() and getLineSelected() Commented May 13, 2021 at 11:19
  • what code inside in getLineSelected ? Commented May 13, 2021 at 11:27
  • It's a simple getter from a variable. i replaced it with 1 with the same result. Commented May 13, 2021 at 11:28
  • Angularjs != Angular, which are you using and update the tag if needed Commented May 13, 2021 at 11:31

2 Answers 2

1

First in your HTML, remove this. in HTML there is no need to write that.

For example:

HTML

<div *ngFor="let i of getCode()" [ngStyle]="{'color': i==getLineSelected() ? 'aqua' : 'black' }">
  {{i}}
  <br>
</div>

TS

 getCode() {
   return [1, 2, 3, 4, 5];
 }

 getLineSelected() {
   return 1;
 }

You can play with my code here.

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

1 Comment

Thanks it works. So the missing [ ] around the ngStyle was the error. What is the meaning of these [ ] ?
0

Try this, You can use let i = index to get the index

<div *ngFor="let code of getCode(); let i = index" [ngStyle] ="{'color': (i==1) ? 'aqua' : 'black'}"> {{i}} <br></div>

Comments

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.