4

in layoutcomponent which is parent I have form. On submit I'm redirecting child component from router-outlet in search component. That's my submit

onSubmit({ value }: { value: Search }) { this.sharedData.searchStr = value.Search; let urlSegments = this.router.url.split('/'); let lang = urlSegments[1]; let url = lang + '/search'; this.router.navigateByUrl(url); this.searchval.reset(); } 

I have shared service and there is interface as suggested here and it works.

import { Injectable, Inject } from '@angular/core'; export interface ISharedModel { searchStr: string; } @Injectable() export class SearchService { sharedComponent: ISharedModel = { searchStr: '' }; constructor() { } } 

in child component I have ngOnInit

ngOnInit() { this.sharedData = this.sharedResource.sharedComponent; this.searchval = new FormGroup({ Search: new FormControl(this.sharedData.searchStr) }); } 

and it have html page

 <form (ngSubmit)="onSubmit(searchval)" [formGroup]="searchval" > <input type="text" placeholder="enter search string" formControlName="Search" class="form-control"> <button class="btn btn-primary">search</button> </form> 

So on redirect application fills this textbox. But when It already is in `mydomain.com/en/search' and I enter search string in parent component it don't updates my child component.

What can I do?

3
  • have you try to use @input decorator on your child component ? If your parameter pass by this input change a event is spread and normaly you should be able to apply your modifications Commented Dec 28, 2016 at 11:21
  • I can't do that. As I know I can pass by input parameter when I have my component's tag somewhere. But I haven't it. I'm redirecting there by router. If I'm not correct tell me Commented Dec 28, 2016 at 11:23
  • Ok i think I haven't well understand your case. Can you publish a pklr or something else to be able to see more precisely your problem ? Thanks. Commented Dec 28, 2016 at 11:29

1 Answer 1

10

You could use a shared service, but you could also just skip that and do the following:

in your ChildComponent declare String Subject:

public static yourString: Subject<String> = new Subject<string>(); 

in your ChildComponent constructor:

YourChildComponent.yourString.subscribe(res => { this.searchval.patchValue({Search: res}) }); 

and in your Parent for example a keyup-method:

updateValue(value) { YourChildComponent.yourString.next(yourUpdated value here) } 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for answer. I tried your answer but my childcomponent has no return.next(false);
Ok, this worked for me when I tested it.... you defined the Subject in your child component, right?
Should I unsubscribe in the ngOnDestroy of the child component?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.