[英]How to pass data on click in angular 5 from parent component to child component?
I want to pass data on button click of parent component to child component and render child component as a separate page in angular 5 instead of rendering child component in parent's template. 我想将父组件的按钮单击时的数据传递给子组件,并在角度5中将子组件渲染为单独的页面,而不是在父模板中渲染子组件。
Suppose, My child component is 'AstronautComponent' and when I add , 假设我的子组件是“ AstronautComponent”,当我添加时,
<app-astronaut *ngFor="let astronaut of astronauts"
[astronaut]="astronaut">
</app-astronaut >
this in parent template it is showing child template on same page instead of separate page.Actually I am able to get data from parent to child but on same parent template.I am using @Input annotation with service(as Observable). 这在父模板中显示在同一页面而不是单独的页面上的子模板。实际上,我能够从父到子获取数据,但在同一父模板上。我在服务中使用@Input批注(作为Observable)。
Kindly Help. 请帮助。
Thanks 谢谢
You can use the router
to open child component in new page like: 您可以使用
router
在新页面中打开子组件,例如:
<a routerLink="/your_link">click here to open child component</a>
and define its path in 并在其中定义其路径
app.module.ts
to open child component like: app.module.ts
打开子组件,如:
{ path: 'your _link', component: child_component }
render child component as a separate page? 将子组件呈现为单独的页面?
Then there is no parent child relationship 那就没有亲子关系
Have a parent component with router outlet 有一个带有路由器插座的父组件
Parent.html Parent.html
<router-outlet></router-outlet>
define routes for your 2 components with data 用数据定义2个组件的路线
{ path: 'your _link', component: child_component, data: { ... any data } } {路径:“您的_link”,组件:child_component,数据:{...任何数据}}
while navigating from component1 to component2 pass the data 从component1导航到component2时传递数据
https://stackoverflow.com/a/36835156/2742156 https://stackoverflow.com/a/36835156/2742156
You can possibly setup Angular routing defining your routes separately for both parent
and astronaut
. 您可以设置Angular路由,分别
parent
和astronaut
定义路线。 Please note these do not have any parent / child relationship anymore. 请注意,这些不再有任何父母/子女关系。
Once you have the data, you may store it in localStorage and navigate / open new tab using 拥有数据后,您可以将其存储在localStorage中,并使用以下方法导航/打开新标签页
window.open('http://127.0.0.1:4200/astronaut', '_blank');
The above statement will render another Angular application in the second tab with the astronaut component rendered. 上面的语句将在第二个选项卡中呈现另一个Angular应用程序,并呈现宇航员组件。 At this point of time in
ngOnInit()
, you may check the localStorage
for the desired data, and if one is present, you can simply access it and show it in HTML as desired. 此时,您可以在
ngOnInit()
检查localStorage
是否有所需的数据,如果存在,则可以直接访问它并根据需要以HTML显示。 This way, you no longer need an @Input()
property. 这样,您不再需要
@Input()
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.