2017-05-23 18 views
2

현재 Angular 2/4를 사용하여 웹 사이트 개발 중입니다. 아무도 날 각도를 사용하여 Div 요소에 클래스를 동적으로 추가하는 방법을 알려주십시오 수 있습니다. 분명히, * ngFor을 통해 표시되는 각 사업부 배경에 임의 부트 스트랩 CSS 색상 클래스를 추가하려고div에 동적으로 클래스 추가

//Component class 
bgarray = ["bg-primary","bg-success","bg-danger","bg-warning","bg-warninig"]; 

getColour() 
{ 
this.bgColour = this.bgarray[Math.floor(Math.random()*this.bgarray.length)]; 
return this.bgColour; 
} 

나는 함수를 호출 [ngClass]를 사용하여 시도와 함수가 "BG-위험"으로 하나의 클래스를 반환 또는 "BG-경고"등

<div class="bg-gray-lighter progress progress-xs"> 
<div class="progress-bar progress-xs " [style.width]="device.value" [ngClass]="getColour()" ></div> 
</div> 

그러나 다음 오류 "expressionChangedAfterItHasBeenCheckedError"다른 backgro에 추가 할 어떤 해결 방법이 있는지

당신이 말해 주 시겠어요를 던졌습니다 다른 진행 막대에 색상을 동적으로?

감사합니다. 당신이 도울 수 있다면 상당히 감사 할 것입니다.

내가 원하는 것을 살짝 들여다 봅니다.

view them here

PS : 이미지가 4를 포함 아래의 진행 표시 줄 수가 다를 수 있지만 그래서 내가 동적으로 그들에게 임의의 색상을 지정하려는, 미래의 16 이상에 도달 할 수 있습니다.

+0

대신 값을 필드에 할당하고 해당 필드에 바인딩하십시오. –

답변

1

시도해보십시오. 타이프 스크립트 파일에서 HTML

<div class="bg-gray-lighter progress progress-xs"> 
<div class="progress-bar progress-xs " [style.width]="device.value" [ngStyle]="getColour()" ></div> 
</div> 

에서

.

public getColour(): any { 
     let style: any = null; 
     style = { 
      'background-color': this.bgarray[Math.floor(Math.random()*this.bgarray.length)] 
     } 
     return style; 
    } 
+0

코드에 대해 고마워, Unfortunatley, 그것은 일하지 않는 캐런 ..하지만 나는 계수를 사용하여 이런 식으로 일하고있다.

user2951306

+0

템플릿에서 컴퓨팅 할 때 성능에 영향을 미칠 수 있습니다 ... [ngStyle] = "getColour()" – Mackelito

1

문제의 근본 원인은 클래스를 "임의"로 계산한다는 것이고, 이것은 각도 변경 감지와 호환되지 않습니다.

각도는 의도적으로 단방향 데이터 흐름을 적용하려고합니다. 이는 템플릿 바인딩 표현식이 모델을 변경할 수 없음을 의미합니다. 이를 확인하기 위해, 개발시 Angular는 뷰가 렌더링 된 후에 변경되지 않도록 제어하며, 렌더링 로직을 두 번 실행하고 이것이 렌더링 엔진에 의해 처음 생성 된 것과 정확히 일치하는지 확인합니다 .

이제 "임의 생성 로직"을 포함하는 바인딩 표현식을 사용하면 두 번째 렌더링에 의해 생성 된 결과가 렌더링 엔진의 첫 번째 실행 중에 생성 된 결과와 같지 않을 수 있습니다. 이것이 expressionChangedAfterItHasBeenCheckedError 오류가 발생하는 이유입니다. 당신은 당신이 배열을 만들 수 ngOnInit() 운전 방식에 비해, 당신의 div의 랜덤 클래스를 지정하려면 http://blog.angular-university.io/angular-2-what-is-unidirectional-data-flow-development-mode/http://blog.angular-university.io/angular-2-redux-ngrx-rxjs/

푸시 :

이러한 링크는 각도에서 단방향 데이터 흐름 메커니즘의 좋은 설명이 div와 같은 무작위 클래스가 많이 있습니다. 이 배열을 사용하여 클래스를 설정할 수 있습니다.

+0

감사합니다. 그렇습니다. – user2951306

0

직접 DOM 조작에 대해 잊지 마세요.
대개 Angular는이 작업을 수행하지만 알고 있어야합니다.코드의 https://plnkr.co/edit/igHxH7I2EJ7HTAN3ymOY?p=preview

미리보기 :

// My stuff 
    activeBg; 
    bgarray  = ["bg-primary", "bg-success", "bg-danger", "bg-warning", "bg-error"]; 

    getRandomBg() { 
    return this.bgarray[Math.floor(Math.random()*this.bgarray.length)]; 
    } 


    updateProgressBtnBg(){ 
    //debugger; 

    // Regular DOM 
    let myProgressBar = document.querySelector(".progress-bar"); 

    if(!this.activeBg){ 
     let newRandomBg = this.getRandomBg(); 
     myProgressBar.classList.add(newRandomBg); 
     this.activeBg = newRandomBg; 
    } else { 
     let newRandomBg = this.getRandomBg(); 
     myProgressBar.classList.remove(this.activeBg); 
     this.activeBg = newRandomBg; 
     myProgressBar.classList.add(this.activeBg); 
    } 

    } 


    onMyButtonClick(){ 
    this.updateProgressBtnBg(); 
    alert("Random background performed from: onMyButtonClick() "); 
    } 


    ngOnInit() { 
    this.updateProgressBtnBg(); 
    alert("Random background performed from: ngOnInit() "); 
    } 
0

나는이 작동 잘 모르겠어요 여기

는 상호 작용하는 예입니다. 그러나 당신은 그것을 시도해 볼 수 있습니다.

<div class="bg-gray-lighter progress progress-xs"> 
<div class="progress-bar progress-xs " [style.width]="device.value 
[ngClass]="{getColour():true}" ></div> 
</div> 


bgarray = ["bg-primary","bg-success","bg-danger","bg-warning","bg-warninig"]; 

getColour() 
{ 
this.bgColour = this.bgarray[Math.floor(Math.random()*this.bgarray.length)]; 
return this.bgColour; 
} 
관련 문제