Subscribe to changes in parent component in Angular

I have a parent component that contains a list of child components. These children are created dynamically and can be of any type.

So what I do is use ng-container as the host in the parent component, create the child components using the ComponentFactoryResolver , and then update some properties in the child component using `` ((component.instance like any) .id = host.id ; `` ``

Here is the code for the parent component (this is a table with several rows):

 <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 is a directive

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

and finally how to create components and update properties

 @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(); } } 

Now, my question. I need the child component to respond to changes in its properties, but since its properties are not occurrences, but just basic properties, I cannot use ngOnChanges inside childComponent. So, is this the way I can subscribe from a child component for changes in the parent component?

I can use ngOnChanges in the Host directive and update the properties in the component, but how then to run some code in the child component?

I have a plunker to check it out. When you click on data1, data2, data3 or data4, the line below should collapse or expand.

Thanks.

+5
source share
2 answers

Child components cannot listen for changes in the parent, but you can notify them of the changes by calling the method instead:

 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 }) } 
+3
source

You can use the emitter event in the child component and access the function in the parent component

https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html https://toddmotto.com/component-events-event-emitter-output-angular-2

0
source

All Articles