问题描述
下面是我在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;
}
}
@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 4中的第n级子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!