Angular 2에서 구성 요소를 다시 렌더링하는 방법은 무엇입니까?
Angular 2에서 구성 요소를 다시 렌더링하는 방법은 무엇입니까? Redux로 작업하는 디버그 목적으로 구성 요소가 다시 렌더링되도록 강제하고 싶습니다. 가능합니까?
변경 감지 후 렌더링이 수행됩니다. 변경 감지를 강제로 수행하여 변경된 컴포넌트 특성 값이 DOM으로 전파되도록 한 다음 (브라우저가 해당 변경 사항을보기에서 렌더링 함) 다음과 같은 옵션이 있습니다.
- ApplicationRef.tick () -Angular 1과 유사합니다.
$rootScope.$digest()
즉, 전체 컴포넌트 트리를 확인하십시오 - NgZone.run (콜백) - 유사
$rootScope.$apply(callback)
- 즉, 각 2 구역 내부의 콜백 함수를 평가합니다. 나는 이것이 콜백 함수를 실행 한 후 전체 구성 요소 트리를 확인하게된다고 확신하지는 않습니다. - ChangeDetectorRef.detectChanges () -비슷한
$scope.$digest()
-즉,이 구성 요소와 그 하위 만 확인
당신은 가져 주입 한 후해야합니다 ApplicationRef
, NgZone
또는 ChangeDetectorRef
구성 요소에.
특정 시나리오의 경우 단일 구성 요소 만 변경된 경우 마지막 옵션을 사용하는 것이 좋습니다.
tx, 내가 필요한 해결 방법을 찾았습니다.
constructor(private zone:NgZone) {
// enable to for time travel
this.appStore.subscribe((state) => {
this.zone.run(() => {
console.log('enabled time travel');
});
});
zone.run을 실행하면 구성 요소가 다시 렌더링됩니다.
ChangeDetectorRef 접근 방식
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
export class MyComponent {
constructor(private cdr: ChangeDetectorRef) { }
selected(item: any) {
if (item == 'Department')
this.isDepartment = true;
else
this.isDepartment = false;
this.cdr.detectChanges();
}
}
다른 답변은 구성 요소의 뷰를 업데이트하는 변경 감지주기를 트리거하는 솔루션을 제공합니다 (전체 다시 렌더링과 동일하지 않음).
전체 사용하여 수행 할 수 있습니다 파괴하고 구성 요소 (보기 모든 라이프 사이클 후크를 호출하고 재건을) 다시 초기화 것이다, 재 렌더링 ng-template
, ng-container
및 ViewContainerRef
다음과 같은 방법으로 :
<div>
<ng-container #outlet >
</ng-container>
</div>
<ng-template #content>
<child></child>
</ng-template>
Then in component having reference to both #outlet
and #content
we can clear outlets' content and insert another instance of child component:
@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;
private rerender() {
this.outletRef.clear();
this.outletRef.createEmbeddedView(this.contentRef);
}
Additionally initial content should be inserted on AfterContentInit
hook:
ngAfterContentInit() {
this.outletRef.createEmbeddedView(this.contentRef);
}
Full working solution can be found here https://stackblitz.com/edit/angular-component-rerender .
I force reload my component using *ngIf.
All the components inside my container goes back to the full lifecycle hooks .
In the template :
<ng-container *ngIf="_reload">
components here
</ng-container>
Then in the ts file :
public _reload = true;
private reload() {
setTimeout(() => this._reload = false);
setTimeout(() => this._reload = true);
}
ChangeDetectorRef.detectChanges()
is usually the most focused way of doing this. ApplicationRef.tick()
is usually too much of a sledgehammer approach.
To use ChangeDetectorRef.detectChanges()
, you'll need this at the top of your component:
import { ChangeDetectorRef } from '@angular/core';
... then, usually you alias that when you inject it in your constructor like this:
constructor( private cdr: ChangeDetectorRef ) { ... }
Then, in the appropriate place, you call it like this:
this.cdr.detectChanges();
Where you call ChangeDetectorRef.detectChanges()
can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges()
appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).
참고URL : https://stackoverflow.com/questions/35105374/how-to-force-a-components-re-rendering-in-angular-2
'development' 카테고리의 다른 글
.xib 파일과 .storyboard의 차이점은 무엇입니까? (0) | 2020.06.08 |
---|---|
SVN 리포지토리 검색 (0) | 2020.06.08 |
libgcc_s_dw2-1.dll이 누락되어 프로그램을 시작할 수 없습니다 (0) | 2020.06.07 |
Fragments를 사용하여 Android의 각 탭마다 별도의 Back Stack (0) | 2020.06.07 |
Mockito : 제네릭이있는리스트 매처 (0) | 2020.06.07 |