简体   繁体   中英

Javascript Angular 4 eventEmitter with ngClass

I am using Angular 4 and eventEmitter to change a class name.

The class css is:

.paintRed {
    background-color: red;
} 

Now for the Angular part:

I have a button component:

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');
  }

}

button.component.html

<p (click)="sendOutEvent()">Click to Emit</p>

Finally on my app.component.ts I have:

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);

  }

}

and my app.component.html looks like this:

<div id="elementId">

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

</div>

The above will successfully add the class "paintRed" to elementId but what I want to do is this:

<div ngClass="myClass">

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

</div>

Basically I want to use ngClass to change the value sent by handleEvent($event) ...

How can I do that?

In your 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;
  }
}

And your html:

<div [ngClass]="myClass">

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

</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM