I have this div
<div class="relative rounded overflow-clip border w-full" [style.aspect-ratio]="media.value.ratio">
<img fill priority [ngSrc]="media.value.src || ftaLogo" [alt]="media.value.caption"
[style.object-fit]="media.value.fit" (click)="insertMedia()">
</div>
at startup, I try to assign the aspect ratio based on a model but it does not apply, what’s the problem?
the aspect ratio of my model is 16:9, even by examining in the browser, my style has never been applied.
But when I change the aspect ratio while the application is running (by clicking on a button) it works.
4
Answers
Sorry everyone. Thanks you for trying to help me.
I founded what was wrong. Data in my local database did not contain the ratio field, that's why ratio doesn't work first time my apologies. 😁😁😁😁
Will delete this Question
Could you try,
aspectRatio
instead ofaspect-ratio
You can also try
[ngStyle]
It sounds like the issue you are experiencing might be related to the timing of when the model data is available for the initial rendering of the template.
When the Angular component is initially rendered, the
media.value.ratio
might not be available yet, causing the[style.aspect-ratio]
binding to be ineffective. However, once the data is available and updated during runtime (e.g., when you click a button tochange
the aspect ratio), the binding works as expected.To ensure that the aspect ratio is set correctly at startup, you can try a couple of approaches:
ngOnInit
lifecycle hook of your component. This ensures that themedia.value.ratio
is available when the component is initialized.TypeScript:
ngIf
directive in the template to conditionally render the div only whenmedia.value.ratio
is available.HTML:
By using one of these methods, you can ensure that the aspect ratio is set correctly at startup and avoid issues with the initial rendering of the template.
In the second approach you provided, you can set the ratio directly in the template without using
ngOnInit
by initializing themedia.value.ratio
in your component. Here’s an example of how you can achieve this:By initializing the
media.value.ratio
in your component, you can directly use it in your template without the need forngOnInit
. Make sure to adjust the paths and values according to your specific requirements.