How add class to parent in angular application?

人盡茶涼 提交于 2019-11-27 06:24:32

问题


I have next HTML

// This is parent
<div class="some-class">
     // This is child
     <totalizer</totalizer>
</div>

How can I change parents style ( add new class ) from child?


回答1:


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.



来源:https://stackoverflow.com/questions/46241271/how-add-class-to-parent-in-angular-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!