将数据传递到Angular 4中的第n级子组件 [英] Pass data to nth level child component in Angular 4

查看:83
本文介绍了将数据传递到Angular 4中的第n级子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在Angular应用程序中的组件结构,

Below is my structure of components in Angular application,

  • app.component.html

  • app.component.html

units.component.html

units.component.html

section.component.html

section.component.html

{{appData.title}}

{{appData.title}}

我正在app.component.ts中创建"appData",我想在子组件的第三级(即在app-section组件中)使用它.

I'm creating "appData" in the app.component.ts and I want to use that in the third level of child component i.e. in the app-section component.

我该如何实现?

推荐答案

使用Angular服务在各个组件之间共享通用数据.以下是执行此操作的步骤.

Use Angular services for sharing your common data across your components. Below are the steps to do that.

步骤1-创建角度服务

import { Injectable, } from '@angular/core';
@Injectable()
export class CommonService {
       sharedData:any; //property for get & set
}

步骤2-从父组件中,您可以将值设置为服务

import { Component, Input} from "@angular/core";
import { CommonService} from "path";

@Component({
    selector: "parent",
    templateUrl: "./ParentComponent.html",
    styleUrls: ["./style.css"],
    providers: [CommonService]
})
export class ParentComponent {

    constructor(
     private commonService: CommonService} 
    ) {

    }
    ngOnInit() {  
          this.commonService.sharedData= "Your Data"
    }

}

第3步-从子组件中访问值

import { Component, Input} from "@angular/core";
import { CommonService} from "path";

@Component({
    selector: "child",
    templateUrl: "./ChildComponent.html",
    styleUrls: ["./style.css"],
    providers: [CommonService]
})
export class ChildComponent {
    someProperty:any;
    constructor(
     private CommonService: CommonService} 
    ) {

    }
    ngOnInit() {  
        this.someProperty=  this.commonService.sharedData;
    }

}

请确保将服务注入到您的App Module中 ,因此您也可以在所有子模块中使用相同的代码.

Please make sure that the service are injected in to your App Module , So you can use the same in all your sub modules also.

@NgModule({
  declarations: [

  ],
  imports: [

  ],
  providers: [CommonService],
  bootstrap: [],

})
export class AppModule { }

如果您想使服务成为双向绑定,请通过此链接

If you want to make the service as two way binding , please go through this link

Angular 2服务双向数据绑定

这篇关于将数据传递到Angular 4中的第n级子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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