Search code examples
eventsangularparenttarget

How to find and add css class to one of div's children?


<div class="post-content-container">
  <div class="post-content">
    Some very long text
  </div>
  <button (click)="showMore($event)">Show more</button>
</div>

<div class="post-content-container">
  <div class="post-content">
    Some very long text
  </div>
  <button (click)="showMore($event)">Show more</button>
</div>

<div class="post-content-container">
  <div class="post-content">
    Some very long text
  </div>
  <button (click)="showMore($event)">Show more</button>
</div>

I'd like to add a class to post-content after click on button. Well, firstly I need to find a parent, right? Then, I'd like to find one of it's children and add to it custom css class.

showMore(event: any) {
  let parent = event.target.parentNode; <-- post-content-container
  //now, how to get into parent's child (I mean post-content) and add to it some custom css class?
}

Solution

  • You are using Angular2 right? There is no need to do any custom JavaScript like you would in jQuery. Here is how to add the class "myClass" by toggling the "showMyClass" value in your component, where the "showMyClass" property is a boolean. Or make "showMyClass" an array of booleans. Here is a full working example:

    import { Component, NgModule } from '@angular/core'
    import { BrowserModule } from '@angular/platform-browser'
    import { FormsModule }   from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      template:`
        <div class="post-content-container">
            <div class="post-content" [ngClass]="{myClass: showMyClass[0]}">
            Some very long text 1
            {{showMyClass[0]}}
            </div>
            <button (click)="showMore(0, $event)">Show more</button>
        </div>
    
        <div class="post-content-container">
            <div class="post-content" [ngClass]="{myClass: showMyClass[1]}">
            Some very long text 2
            {{showMyClass[1]}}
            </div>
            <button (click)="showMore(1, $event)">Show more</button>
        </div>
      `
    })
    export class App {
        public showMyClass: Array<boolean>;
    
        constructor(){
          this.showMyClass = [];
        }
    
        showMore(index, event: any) {
          this.showMyClass[index] = !this.showMyClass[index];
        }
     }
    
    
    @NgModule({
      imports: [ BrowserModule, FormsModule ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}