How Add Class to Parent in Angular Application

How add class to parent in angular application?

You can use an EventEmitter @Output() property that signals the parent component to add/remove a css class dynamically using ngClass.

In your child totalizer component, define,

@Output() cssRefresh = new EventEmitter<boolean>();

//when you need to add/remove css emit an event out to the parent like this
// (preferably in a method in this component),

this.cssRefresh.emit(true); // or 'false' depending on add/remove

Then in the parent html modify this,

<div class="some-class" [ngClass]="{ 'dynamicClass1 dynamicClass2 dynamicClass3': addCss}">
// This is child
<totalizer (cssRefresh)=refreshCss($event)></totalizer>
</div>

Inside your parent component add this method and property,

addCss = false; // set 'initial state' based on your needs

refreshCss(add: boolean) {
this.addCss = add ? true : false;
}

More on ngClass here.

Angular: How to Add a class to Parent when Click on a Child Element

addClassToParent() {
this.clickEventXXX = true
}
<div class="parent" [class.parent-style]="clickEventXXX"> // This is parent
<div class="child" (click)="addClassToParent()"></div>// This is child
</div>

How to add a CSS class to Angular parent when using router-outlet for child

You can inject the Router into your parent component, and use [ngClass].

constructor(public router: Router) { }

Then in the template:

<div class="container" [ngClass]="{'test' : router?.url === '/home'}">

<router-outlet></router-outlet>
</div>

This will add a class called test if the router is set to /home.

You can see it in action here

How to add class to parent's parent's div in Angular JS?

You could maybe use ng-class to apply the class when you set a boolean to true. For example :

 <div class="test" ng-repeat="test in tests" ng-class="{'hide' : onProcessAnswer}">

and in your controller

$scope.onProcessAnswer = false;
$scope.processAnswer = function(isRight, event) {
...
$scope.onProcessAnswer = true;
...
}

Angular2 add class to parent component on child event execution

Well, I finally resolved the issue using the @Output decorator.

I added a changedFocus property to the searchBar component:

@Output() changedFocus : EventEmitter<boolean> = new EventEmitter<boolean>();

And as well added the event handlers in the searchbar:

  /**
* executed when the form is focused
*/
focus(){
this.changedFocus.emit(true);
}

/**
* executed when the form is blured
*/
blur(){
this.changedFocus.emit(false);
}

Then, in the Header component I added a focused property:

private focused : boolean;

And a changeFocus method:

  /**
* change element focus
*/
changeFocus(){
this.focused = !this.focused;
}

Which is executed everytime the focus state changes on the child component.
That gave me the wanted result.



Related Topics



Leave a reply



Submit