使用ngStyle时出现“Cannot find a differ supporting object”错误求助
Hey there! Let's break down why you're running into this error and how to fix it quickly. That error usually pops up when Angular's ngStyle doesn't get the format it expects—let's walk through the solutions step by step.
First: Correct the ngStyle Syntax
The biggest issue here is how you're using ngStyle. It expects a bound object (via square brackets []), not a string with interpolation. Your original code uses ngStyle="max-width:{{redrated}}%" which doesn't follow Angular's property binding rules. Even your test with ngStyle="{'max-width': '20px' }" is missing the square brackets, so Angular can't parse it properly.
Fix 1: Use Proper Property Binding for ngStyle
Here's the corrected HTML code with the right ngStyle syntax:
<div class="progress-bar-line red" role="progressbar" aria-valuenow="{{redrated}}" aria-valuemin="0" aria-valuemax="100" [ngStyle]="{ 'max-width': redrated + '%' }"> <span class="title">{{ redrated }}%</span> </div>
- The
[ngStyle]tells Angular to evaluate the expression inside as an object. - We're creating an object where the
max-widthproperty is set toredratedconcatenated with%(so ifredratedis 60, it becomes"60%").
Fix 2: Ensure redrated is a Primitive Type
Another common cause of this error is if redrated isn't a number or string (like if it's an array, object, or Observable that hasn't been resolved). Double-check your component code to make sure it's a primitive value:
// In your component .ts file redrated: number = 50; // Initialize with a number, or set it from an API call // If you're fetching it asynchronously (e.g., from an Observable), use async pipe or subscribe properly: // redrated$ = this.yourService.getRating(); // Then in HTML: [ngStyle]="{ 'max-width': (redrated$ | async) + '%' }"
If redrated was accidentally set to an array or object, Angular can't compute the "differ" (change detection) for it, hence the error.
Fix 3: Test with a Hardcoded Value First
To rule out issues with redrated, test with a fixed value to confirm the syntax works:
<div class="progress-bar-line red" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" [ngStyle]="{ 'max-width': '75%' }"> <span class="title">75%</span> </div>
If this works, the problem was definitely with how redrated was defined or passed to ngStyle.
Why Your Previous Attempts Failed
ngStyle="max-width:{{redrated}}%": Angular treats this as a plain string, not a style object, so it can't process the dynamic value correctly.- Missing square brackets on
ngStyle: Without[], Angular doesn't evaluate the expression as a binding—it just treats it as static text.
Give these fixes a try, and your progress bar should start working as expected!
内容的提问来源于stack exchange,提问作者Anjuman Barui

