I'm trying to add a conditional CSS class to a Material element in Angular using NgClass. I want a CSS class added based on the current route.
Here is the html:
<mat-expansion-panel-header [ngClass]="activeSection('accountsettings')">
<mat-panel-title>
Account Settings
</mat-panel-title>
</mat-expansion-panel-header>
Here is the typescript: selectedClass: string;
public activeSection(name: string) {
this.router.events.subscribe((event: any) => {
if(event instanceof NavigationEnd){
const section = event.url.replace("/accountmanagement/", "");
if (section == name) {
this.selectedClass = 'sectionactive';
} else {
this.selectedClass = '';
}
return this.selectedClass;
}
}
);
}
This is my SCSS:
.sectionactive {
background-color: teal !important;
}
I get an error saying Type 'void' is not assignable to type 'string | string[] | Set<string> | { [klass: string]: any; }'.
on the [ngClass] line in the html. I don't understand why I would be getting this error since you can use a function with NgClass and return a string.
CodePudding user response:
I figured it out. I had the return statement in the wrong place.
This works:
public activeSection(name: string) {
this.router.events.subscribe((event: any) => {
if(event instanceof NavigationEnd){
const section = event.url.replace("/accountmanagement/", "");
if (section == name) {
this.selectedClass = 'sectionactive';
} else {
this.selectedClass = '';
}
}
}
);
return this.selectedClass;
}
CodePudding user response:
Your'e function in the first atemp return nothing, is the reason because the error. You rsecond aproach is not better, you return a variable, but this variable is not actualize when you call the function
The solution is simple store in a variable the "section"
section:string=null;
ngOnInit(){
this.router.events.subscribe((event: any) => {
if(event instanceof NavigationEnd){
this.section = event.url.replace("/accountmanagement/", "");
}
}
and use
<mat-expansion-panel-header
[ngClass]="section=='accountsettings'?'sectionactive':null)">
//or simply
<mat-expansion-panel-header
[class.sectionactive]="section=='accountsettings'">
NOTE: You can not think is some like
/*NOT WORK**/
public activeSection(name: string) {
return this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map((event: RouterEvent) => event.url.replace('/accounmanagement', '') == name
? 'sectionactive'
: null
)
);
}
to make some like
/*NOT WORK*/
<p [class]="activeSection('/')|async">
because when the navigationEnd the page is not renderer yet