I am attempting to add a class based off of whether or not a value is present in storage, or set to a specific value. I am attempting to use [ngClass] for this. For some rea
If you have a method in your binding, it will be called every time change detection runs.
If you need to update parent button by clicking on another parent button, try this:
Template:
<button (click)="updateLockClass()">Click to update</button>
<button type="button" [ngClass]="lockClass">Button with "lockClass</button>
App component:
export class AppComponent {
lockClass = "";
checkClass(num) {
return num == 2;
}
updateLockClass() {
this.lockClass = this.checkClass(2) ? "lockClass2" : "lockClass";
}
}
If you need to update child button by updating parent value that gets parsed into child component, try this:
parent component:
<app-child [childMessage]="parentMessage"></app-child>
<input [(ngModel)]="parentMessage">
child.component.html
<button type="button" [ngClass]="childClass">Child Button with "childClass"</button>
child.component.ts
import { Component, Input, OnChanges, SimpleChanges } from "@angular/core";
@Component({
selector: "app-child",
templateUrl: "./child.component.html",
styleUrls: ["./app.component.css"]
})
export class ChildComponent implements OnChanges {
childClass = "";
@Input() childMessage: string;
checkClass(num) {
return num == 2;
}
updateChildClass() {
this.childClass = this.checkClass(2) ? "lockClass3" : "lockClass";
}
constructor() {
}
ngOnChanges(changes: SimpleChanges) {
console.log('Change detected:', changes.childMessage);
if (changes.childMessage.currentValue != "Change parent value!") {
this.updateChildClass();
}
}
}
Link to codesandbox: https://codesandbox.io/s/1y4wnz423