首页 文章

从父级更新子组件

提问于
浏览
2

layoutcomponent 这是我有父母的形式 . 提交时,我正在搜索组件中的 router-outlet 重定向子组件 . 那是我的提交

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();
}

我有共享服务,有界面as suggested here,它的工作原理 .

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

    sharedComponent: ISharedModel = {
      searchStr: ''
    };

    constructor() { }
}

在子组件中我有 ngOnInit

ngOnInit() {
    this.sharedData = this.sharedResource.sharedComponent;

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

它有html页面

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

因此,在重定向应用程序上填充此文本框 . But 当它已经在`mydomain.com/en/search ' and I enter search string in parent component it don' t更新我的子组件 .

我能做什么?

1 回答

  • 5

    您可以使用共享服务,但您也可以跳过它并执行以下操作:

    在您的ChildComponent中声明 String Subject

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

    在您的ChildComponent构造函数中:

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

    在您的父母中,例如 keyup -method:

    updateValue(value) {
       YourChildComponent.yourString.next(yourUpdated value here)
    }
    

    编辑:工作plunker

相关问题