加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 从父级更新子组件

发布时间:2020-12-17 17:27:52 所属栏目:安全 来源:网络整理
导读:在layoutcomponent中,我是父表单.在提交时,我正在从搜索组件中的路由器插座重定向子组件.那是我的提交 onSubmit({ value }: { value: Search}) { this.sharedData.searchStr = value.Search; let urlSegments = this.router.url.split('/'); let lang = urlS
在layoutcomponent中,我是父表单.在提交时,我正在从搜索组件中的路由器插座重定向子组件.那是我的提交

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>

因此,在重定向应用程序上填充此文本框.但是当它已经在`mydomain.com/en/search’并且我在父组件中输入搜索字符串时,它不会更新我的子组件.

我能做什么?

解决方法

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

在您的ChildComponent中声明String主题:

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

在您的ChildComponent构造函数中:

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

在你的父亲中,例如一个keyup方法:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读