WebTechie
WebTechie

Reputation: 39

How to pass data to child component which is routed from parent component?

I am routing to a child component using a button from the parent component's HTML template. How to pass parent component's data (say name) to child component? I don't want to display the data in the URL (displays if passed in [routerLink] - to navigate to child component)

Upvotes: 1

Views: 1513

Answers (3)

F.Strathaus
F.Strathaus

Reputation: 39

if your child component is inside of your parent component, you can pass data as an input argument. Take a look here: https://angular.io/api/core/Input

In your parent component, set the data you want to pass to the child component like this:

<child-component [inputdata]="yourDataObject">

where "inputdata" is a name you can choose and "yourDataObject" is the attribute you want to pass to your child component. In your child component you can retrieve your data like this:

@Input('inputdata') passedData;

Of course the name has to be the same as passed in your parent component.

Upvotes: 0

buzzwauld
buzzwauld

Reputation: 36

Try sharing the state generally via a service.

Create a service:

@Injectable()
export class SomeService {
  data: string;
}

You can then include this in both source and target components.

@Component({
   ...
})
export class SourceComponent {
  constructor(private service: SomeService) {}

  onSomeAction() {
    service.data = "Some Data";
    // Route to your component.
  }
}

then consume it like this:

@Component({
  ...
})
export class TargetComponent {
  data: string;
  constructor(private service: SomeService) {} 

  ngOnInit() {
    this.data = this.service.data;
  }
}

You will also need to add SomeService to the hosting module:

@NgModule({
  imports:      [ ... ],
  providers:    [ SomeService ],
  declarations: [ SourceComponent, TargetComponent ]
})

For something more complicated you could look at packages like https://ngxs.gitbook.io/ngxs, which provides several powerful features for handling state management in angular.

Upvotes: 0

Gautam
Gautam

Reputation: 238

What I understand from your question is that you want to send data from parent route to child route without display the actual URL and without using router link to avoid showing actual links. If that so, you can design as below:-

In your html, you can use a link type button using bootstrap4 and you need to add onclick function as below :-

<button type="button" class="btn btn-link" (click)="gotochildroute()" >Link</button>

In gotochildroute() method, use routing as below:-

this.route.navigate(['childroute'], {skipLocationChange: true}); 

If you are using link then you can skipLocationChange as below:-

<a [routerLink]="['/childroute'}]" replaceUrl="false" skipLocationChange="true"> </a>

Hope this will helpful.

Upvotes: 0

Related Questions