我正在使用 Angular 4 和 eventEmitter 来更改类名称。
CSS 类是:
.paintRed {
background-color: red;
}
现在是 Angular 部分:
我有一个按钮组件:
button.compoment.ts:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss']
})
export class ButtonComponent implements OnInit {
@Output() outputEvent: EventEmitter<any> = new EventEmitter();
constructor() { }
ngOnInit() {}
sendOutEvent() {
this.outputEvent.emit('paintRed');
}
}
按钮.component.html
<p (click)="sendOutEvent()">Click to Emit</p>
最后在我的 app.component.ts 上我有:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
handleEvent(value) {
console.log(value);
document.getElementById('elementId').classList.add(value);
}
}
我的 app.component.html 看起来像这样:
<div id="elementId">
<app-button (outputEvent)="handleEvent($event)"></app-button>
</div>
上面将成功地将类“paintRed”添加到elementId,但我想要做的是:
<div ngClass="myClass">
<app-button (outputEvent)="handleEvent($event)"></app-button>
</div>
基本上我想使用ngClass来更改handleEvent($event)发送的值...
我怎样才能做到这一点?
最佳答案
在你的app.component.ts中
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
myClass = '';
handleEvent(value) {
console.log(value);
myClass = value;
}
}
还有你的 html:
<div [ngClass]="myClass">
<app-button (outputEvent)="handleEvent($event)"></app-button>
</div>
关于带有 ngClass 的 Javascript Angular 4 eventEmitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850354/