2017-10-20 4 views
0

私は、Angular 4とeventEmitterを使用してクラス名を変更しています。Javascript Angular 4 eventEmitter with ngClass

クラスCSSは次のとおりです。

.paintRed { 
    background-color: red; 
} 

今角部のために:

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

私が持っている私のapp.component.tsの最後に210
<p (click)="sendOutEvent()">Click to Emit</p> 

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するのではなく、私がやりたいことは、このされています。基本的に私はVを変更するngClassを使用したい

<div ngClass="myClass"> 

    <app-button (outputEvent)="handleEvent($event)"></app-button> 

</div> 

ハンドルイベント($ 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で

答えて

3

<div [ngClass]="myClass"> 

    <app-button (outputEvent)="handleEvent($event)"></app-button> 

</div> 
+0

うん、OPは "という角度を伝えるために必要とされるngClass''周りの2つの角かっこを逃しましたmyClass "はローカル変数であり、文字列ではありません。 – mauris

+1

これと 'myClass'は存在しません。 – UncleDave

関連する問題