I am trying to conditionally set a classname based on a boolean variable. I have set the variable within the parent component:
public alteredSidebar: boolean;
And this is my though process behind conditionally defining which class it is:
<div [class]="alteredSidebar == false ? 'secondsidenav' : 'sidenav'" id="rollup-sidenav" [ngClass]="{ 'greyout': greyOut }"></div>
I have defined 2 classes with css file, one called secondsidenav and another called sidenav. Wherever I set the boolean as false, I would like the classname to equal the secondsidenav and where it is not false it be sidenav. Here is an instance of where I am using it and I am expecting the class to be set to 'secondsidenav':
<app-rollup [data]="rollupData" (resetCalled)="onRollupReset()" (entrySelected)="onRollupSelectEvent($event)" [alteredSidebar]="false">
</app-rollup>
However I am getting the following error: "Can't bind to 'alteredSidebar' since it isn't a known property of 'app-rollup'."
use @Input()
decorator on it
@Input()
public alteredSidebar: boolean;
As @junk said, you should use the @Input() decorator in the app-rollup component and I'd like to add, do not mix [className] with ngClass, this might not be related to your problem but it gets really buggy if you're using a reactive property to programatically add or remove a class, just pick one and try not to mix them it will also make the code more consistent. Oh, and the correct syntax is [className] you're probably confusing it with [class.foo]="expresion" which will apply the 'foo' class if the expression is true
Personally I'd do something like this, also sticking with one approach is considered a best practice
<div id="rollup-sidenav" [ngClass]="{
'greyout': greyOut,
'secondsidenav': !alteredSidebar,
'sidenav': alteredSidebar
}">
</div>
Hope that helps, let me know if it doesn't!
@Berheet.. try this
assign the value alteredSidebar
in the component itself and pass it like below
parentComponent.ts
public alteredSidebar: boolean = false;
parentComponent.html
<app-rollup [data]="rollupData" (resetCalled)="onRollupReset()" (entrySelected)="onRollupSelectEvent($event)" [alteredSidebar]="alteredSidebar">
</app-rollup>
Add Input in child component
childComponent.ts
@Input() alteredSidebar: boolean;
childComponent.html
<div [class]="alteredSidebar == false ? 'secondsidenav' : 'sidenav'" id="rollup-sidenav" [ngClass]="{ 'greyout': greyOut }"></div>
I'd suggest to simply set the div-tags class property conditionally as follows
[class]="alteredSidebar ? 'sidenav' : 'secondsidenav'"
This way you get a more readable condition ? positive case : negative case flow and you don't need to compare your variable to anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.