Using @Input between parent and child component via routing module in Angular

586 views Asked by At

This is parent component :

parent.component.ts ==>

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-parent',
  templateUrl: '<div>
                 <h1>I am the parent</h1>
                 <p>{{textForChild}}</p>
                </div>'
})
export class ParentComponent implements OnInit {

  @Input() textForChild!: string;

  constructor() {}

  ngOnInit(): void { }

}

And this is the app-routing.module.ts ==>

{
    path: '',
    component: ParentComponent,
    children: [
      {
        path: 'children-url',
        loadChildren: () =>
          import('@modules/child.module').then((m) => m.ChildModule),
      }
    ],
  },

\\\\\\\\\\\\\

And This is Child Component :

child.module.ts ==>

const routes: Routes = [
  {
    path: ':id',
    component: ChildComponent,
  },
];

@NgModule({
  declarations: [ChildComponent],
  imports: [RouterModule.forChild(routes)],
})

The question is,
if I code in child.component.html, how to fill the textForChild above?

1

There are 1 answers

1
AbdulKareem On

One way is injecting ParentComponent inside ChildComponent constructor.

@Component({...})
class ChildComponent {

   constructor(parent:ParentComponent) {
   // access properties of parent here
   parent.textForChild
   }
}

Note: This approach has a very big disadvantage i.e. Now you child component can only used under ParentComponent