Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update child component from parent

Tags:

angular

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?

like image 931
gsiradze Avatar asked Dec 23 '22 22:12

gsiradze


1 Answers

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)
}
like image 122
AT82 Avatar answered Dec 28 '22 09:12

AT82