2016-08-12 6 views
1
<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> 

버튼을 클릭 한 후 post-content에 수업을 추가하고 싶습니다. 음, 먼저 부모를 찾아야 해, 그렇지? 그런 다음 그 중 하나를 찾아서 맞춤 CSS 클래스를 추가하고 싶습니다.div의 자식 중 하나에 CSS 클래스를 찾아 추가하는 방법은 무엇입니까?

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? 
} 

답변

1

오른쪽 각도 2를 사용하고 있습니까? jQuery에서와 같이 사용자 정의 JavaScript를 수행 할 필요가 없습니다. 다음은 "showMyClass"속성이 부울 값인 구성 요소의 "showMyClass"값을 토글하여 "myClass"클래스를 추가하는 방법입니다. 또는 "showMyClass"에 부울 배열을 만듭니다. 다음은 전체 작동 예제입니다.

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 {} 
+0

음, 아마도 내 게시물이 분명하지 않을 수 있습니다. 게시물 콘텐츠 div와 게시물 콘텐츠 컨테이너가 두 개있을 수 있으며 해당 클래스를 모두 추가하지 않으려합니다. 그 버튼을 클릭 한 곳에서만 그 클래스를 추가하고 싶습니다. – elzoy

+0

업데이트 된 요구 사항으로 내 대답을 업데이트했습니다 :-) 단일 속성 대신 "showMyClass"에 부울 배열을 사용하고 있습니다. 최고의 구현은 아니지만 작동하지만 아이디어를 얻을 수 있습니다. –

+0

감사합니다. 너 나 좋은 생각이야. 나는 인덱스 사용법과 조금 다르다. – elzoy