<nav class="navbar navbar-expand-lg fixed-top" [ngStyle]="navBg">
Html In the project I developed with Angular, the [ngStyle]=”navBg” field in this tag in the HTML gives an error.
navBg: any;
@HostListener('document:scroll') scrollover() {
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
this.navBg = {
"background-color": "#000000"
}
}
else {
this.navBg = {}
}
}
This is my typscript file. What is the reason for the error?
I got this error while developing a Clone project. I’m still in the learning phase
Yusuf Güner is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
You must import either NgStyle
or CommonModule
for the directives, ngStyle
or ngClass
to work.
If its standalone -> the imports should be in the imports array of the component.
If its modular -> go to the module, where the component is added to the declarations array and add the import
import { Component, HostListener } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
styles: [`:host {height: 200vh;display:block;}`],
template: `
<h1 [ngStyle]="navBg">Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
`,
})
export class App {
navBg: any;
name = 'helo';
@HostListener('document:scroll') scrollover() {
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
this.navBg = {
'background-color': '#000000',
};
} else {
this.navBg = {};
}
}
}
bootstrapApplication(App);
Stackblitz Demo