将价值从父母传递给孩子 [英] pass value from parent to child

查看:89
本文介绍了将价值从父母传递给孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的layout.html

this is my layout.html

<form (ngSubmit)="onSubmit(searchval)" [formGroup]="searchval">
                    <input type="text" class="form-control" required formControlName="Search" placeholder="{{ 'General.Search' | translate }}">
                    <button type="submit"></button>
</form>

在我的layout.component.ts中,我拥有:

and in my layout.component.ts I have:

onSubmit({ value }: {
        value: Search
    }) {
        this.search.getSearchResult(value.Value);
    }

在该服务中,我正在执行http get:

in that service I'm doing http get:

getSearchResult(val: string) {
    this.httpCall.get('/pub/home/search?val=' + val)
        .subscribe(
        data => {
            console.log(data);
        });
}

现在,我想将该数据传递给我的 layout组件的子组件.我该怎么办?

Now I want to pass that data to child component of my layout component. How can I do that?

我想在另一个名为search.component的页面中重定向用户,但我不希望我的搜索字符串位于url中.所以

I want to redirect user in another page called search.component but I don't want that my search string to be in url. so

mydomain.com/home
mydomain.com/search

不是

mydomain.com/search?val=something

推荐答案

创建一个共享接口,并从子级设置值并从父级获取值,如下所示:

Create a shared interface and set value from child and get from parent as below:

接口:

import {Injectable} from "@angular/core";

export interface SharedModel {
    Name: string;
}

@Injectable()
export class Shared {

    SharedComponent: SharedModel = {
        Name: ''        
    };

    constructor() {       
    }
}

父/子组件:

import {Shared, SharedModel}    from '../Shared';

public sharedData: SharedModel;
constructor(private sharedResource: Shared) {
    this.sharedData = sharedResource.SharedComponent;
}

设置值:

this.sharedData.Name="Sandip Patel";

获得价值:

console.log(this.sharedData.Name);

这篇关于将价值从父母传递给孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆