2017-05-15 11 views
5

하위 구성 요소 목록을 호스트하는 상위 구성 요소가 있습니다. 이 하위 항목은 동적으로 생성되며 모든 유형이 될 수 있습니다.상위 구성 요소의 변경 사항을 각도로 구독하십시오.

부모 구성 요소에서 호스트로 ng-container을 사용하고 ComponentFactoryResolver으로 하위 구성 요소를 만든 다음```(component.instance as any) .id를 사용하여 하위 구성 요소의 일부 속성을 업데이트합니다. = host.id,``여기서

부모 구성 요소에 대한 코드 (이는 테이블 일부의 행으로의)

<tr class="table-collapse__item" [class.active]="company === selected"> 
    <td [attr.colspan]="getItemColspan()"> 
    <ng-container host [id]="name" [selected]="isSelected"></ng-container> 
    </td> 
</tr> 

host는 지시자

@Directive({ 
    selector: '[host]' 
}) 
export class Host implements OnChanges { 
    @Input() id: any; 
    @Input() selected: boolean; 
    constructor(public viewRef: ViewContainerRef) {} 
} 

마지막 방법 속성 이제

@ViewChildren(Host) hosts: QueryList<Host>; 

    constructor(private resolver: ComponentFactoryResolver, 
       private cd: ChangeDetectorRef) {} 

    ngAfterViewInit() { 
    if (this.hosts) { 
     const componentFactory = this.resolver.resolveComponentFactory(this.inner); 
     this.hosts.forEach((host: Host) => { 
     const component = host.viewRef.createComponent(componentFactory); 
     (component.instance as any).id = host.id; 
     (component.instance as any).selected = host.selected; 
     }); 
     this.cd.detectChanges(); 
    } 
    } 

, 내 질문에 구성 요소를 생성하고 업데이트합니다. 자식 구성 요소가 해당 속성의 변경에 반응해야하지만 해당 속성은 입력이 아니라 기본 속성이므로 childComponent 내부에서 ngOnChanges를 사용할 수 없습니다. 따라서 하위 구성 요소에서 상위 구성 요소의 변경 사항에 가입 할 수있는 방법이 있습니까?

호스트 지시문에서 ngOnChanges를 사용하고 구성 요소의 속성을 업데이트 할 수 있지만 하위 구성 요소에서 일부 코드를 트리거하는 방법은 무엇입니까?

나는 이것을 테스트하기 위해 plunker이 있습니다. data1, data2, data3 또는 data4를 클릭하면 아래 행이 축소되거나 확장됩니다.

감사합니다.

답변

3

하위 구성 요소가 부모의 변경을들을 수는 없지만, 당신이 그들을 알릴 수있는 하위 구성 요소에서 이벤트 이미 터를 사용하고 부모 구성 요소의 기능에 액세스 할 수 있습니다 대신에 자식에 대한 메서드를 호출하여 변경 사항에 대해 :

components = []; 
ngAfterVeiwInit() { 
if (this.hosts) { 
    const componentFactory = this.resolver.resolveComponentFactory(this.inner); 
    this.hosts.forEach((host: Host) => { 
     const component = host.viewRef.createComponent(componentFactory); 
     (component.instance as any).id = host.id; 
     (component.instance as any).selected = host.selected; 
     this.components.push.components(); 
    }); 
    this.cd.detectChanges(); 
    }  
} 

ngOnChanges() { 
    this.components.forEach((c) => { 
    c.instance.ngOnChanges(); // or any other method the child comonents have 
    }) 
} 
+0

감사! 하지만 나는''TypeError : innerComponents [this.id] .ngOnChanges가 함수가 아닌''오류가 발생합니다 .''는 innerComponents입니다. 답안에서 제안한 배열입니다. 내 ChildComponent는 OnChanges를 구현하지만 그 방법이 있습니다. – David

+0

'this.id' 란 무엇입니까? 구성 요소에는 실제로'ngOnChanges' 메소드가 있습니까? 또한'.instance'가 누락되었습니다 –

+0

죄송합니다, 맞습니다. 인스턴스가 없습니다. 고마워, 고마워 !! – David

관련 문제