1

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.. I see it works.. But do you have any suggest to another way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.