2017-01-18 1 views
4

여러 양식 구성 요소를 사용하여 양식을 작성하는 응용 프로그램이 있습니다. 이제 기존의 객체를 나열하는 일종의 외래 키 필드를 만들고 '추가'버튼을 표시하려고합니다. 이 버튼은 모달 대화 상자에 다른 폼 구성 요소를 표시합니다. '하위'양식은 <ng-content>을 사용하여 간단히 표시됩니다. 이 모든 것이 완벽하게 작동합니다.구성 요소의 동적 하위를 관찰 할 수 있습니까?

상황을 설명하겠습니다.

<form class="form"> 
    <form-field> 
     <another-form-component (save)="handleSave()"></another-form-component> 
    </form-field> 
</form> 

<form-field>의 템플릿 :이 save 이벤트의 대한

<modal-dialog-component [(visible)]="showForm"> 
    <!-- 
     Here the <another-form-component> which was passed 
     to <form-field> is added: 
    --> 
    <ng-content></ng-content> 
</modal-dialog-component> 
<div class="form-field"> 
    <select> <!-- existing options --> </select> 
    <button (click)="openForm($event);">Create new</button> 
</div> 

당신이 <another-form-component>을 볼 수 있듯이이 @Output()을 가지고이 <form-component>의 템플릿입니다. 이것은 EventEmitter입니다.

내 질문은 : <form-field> 구성 요소의 EventEmitter에 어떻게 구독 할 수 있습니까? 양식을 저장할 때를 알고 싶습니다. <modal-dialog>을 닫을 수 있습니다.

기억하십시오 : 양식은 <ng-content>을 사용하여 전달됩니다. @ViewChildren을 사용하여 <form-field>의 자식을 가져오고 어떤 종류의 addEventListener() 메서드를 사용할 수 있습니까? 그런 존재조차 존재합니까?

희망을 보내주세요.

인사말, 요한

당신은 당신의 <form-field> 구성 요소 클래스에서 ContentChildren를 조회하고 그들이 다음과 같은 방출 이벤트를 구독 할 수 있습니다

답변

2

:

export class FormFieldComponent implements AfterContentInit { 

    @ContentChildren(AnotherFormComponent) anotherFormComponents: QueryList<AnotherFormComponent>; 

    ngAfterContentInit() { 
     console.log('anotherFormComponents: ', this.anotherFormComponents.toArray()); 

     this.anotherFormComponents.toArray()[0].save.subscribe(valueEmitted => { 
      console.log('Value emitted from the anotherFormComponents[0]: ', valueEmitted); 
     }); 
    } 
} 

QueryListAnotherFormComponent가 추가 될 때마다, 업데이트, 제거 또는 이동됩니다 . 당신은 QueryList.changes 관찰 가능한에 가입하여 변경 사항을 '관찰'할 수

ngAfterContentInit() { 
    this.anotherFormComponents.changes.subscribe(qList => { 
     console.log('Changed list: ', qList); 
    }); 
} 

을, BTW는 알고 가치 : 최고 What's the difference between @ViewChild and @ContentChild?

+1

! 나는 이것을 바로 구현할 것입니다! – Johan