使用路由器出口时,使用Input属性将值从一个组件传递到另一组件 [英] Passing value from one component to other component using Input property when using router-outlet

查看:93
本文介绍了使用路由器出口时,使用Input属性将值从一个组件传递到另一组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的父组件,其中的定义为在路由更改时显示其他组件(childComponent),我想将值从parentComp传递给childComp,如果我们不这样做,通常我们会在选择器的位置添加选择器来代替router-outlet使用路由并使用@Input属性传递.使用路线时如何实现相同目的

I have my parent component where the is defined to display other component(childComponent) when the route changes, I want to pass a value from parentComp to childComp, usually we include the selector in place of router-outlet if we don't use routes and pass using @Input property. How can I achieve the same when using routes

ParentComponent

ParentComponent

@Component({
    selector : 'parent',
    template : `<h1>Home</h1>
            <router-outlet test1="test"></router-outlet>
    `,
})
export class parentComp{
    test = "testing";
}

ChildCompoent

ChildCompoent

@Component({
    selector : 'child',
    template : `<h2>Home</h2>
    `,
})
export class childComp implements onChanges, onInit{
    @Input() test1;
    ngOnChanges(){
        console.log(this.test1);
    }
ngOnInit(){
            console.log(this.test1);
}
}

我想从父组件到子组件获取test1的值,并使用@Input属性在控制台中打印.

I want to get the value of test1 from parent to child component and print in console using @Input property.

在控制台中打印值时,我得到的test1值未定义

I'm getting the value of test1 as undefined when printing the value in console

推荐答案

您不能为 router-outlet 定义 @Input()变量.

相反,您可以选择以下选项

Instead you have the following as alternative options

  • 使用Route参数
  • 使用查询参数
  • 共享服务以共享数据
  • 使用redux工具进行状态管理

这篇关于使用路由器出口时,使用Input属性将值从一个组件传递到另一组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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