angularangular-componentsproperty-binding

Angular | Parent component being passed as input to child


I recently started working on an Angular project and noticed a practice that I thought was a bit odd. In this case, the connection between a parent and child component was being made by passing the parent component itself as input to the child.

Parent Class Component

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent {
    ...
}

Parent Template Component

<div>
    <app-child [parent]="this"></app-child>
</div>

Child Class Component

@Component({
    selector: 'app-child',
    templateUrl: './child .component.html',
    styleUrls: ['./child .component.css']
})
export class ChildComponent {
    @Input() parent: ParentComponent;
}

Just wanted to know if this is common or is it bad practice? Well I found it very strange


Solution

  • Never seen this practice before, although I took part in the development in a lot of projects. I see there only two reasons we might need this, it's when we don't know what the parent component might be, or wanna get it's context. But we can do almost the same with this constructor.

    constructor(@Inject(ParentComponent) private parent: ParentComponent){
      ...some code
    }
    

    So, we can't say, is this good or bad. It depends on what approach your team uses. However, it would be nice to work on architecture of application, if it came to this.