我有下面的HTML
// This is parent
<div class="some-class">
// This is child
<totalizer</totalizer>
</div>
如何从子元素更改父元素的样式(添加新类)?
我有下面的HTML
// This is parent
<div class="some-class">
// This is child
<totalizer</totalizer>
</div>
EventEmitter
@Output()
属性,通过使用ngClass
让父组件动态地添加或删除一个css
类。在您的子组件totalizer
中定义如下:@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
html
中进行修改。<div class="some-class" [ngClass]="{ 'dynamicClass1 dynamicClass2 dynamicClass3': addCss}">
// This is child
<totalizer (cssRefresh)=refreshCss($event)></totalizer>
</div>
addCss = false; // set 'initial state' based on your needs
refreshCss(add: boolean) {
this.addCss = add ? true : false;
}
关于ngClass
的更多信息,请点击这里。