我有四个组件,我需要将数据从父级传递给子级。
map.html
模板中的结构看起来像这样:
<map-builder [width]="width">
<layer [name]="'markerLayer'">
<marker [lat]="8.5" [lng]="55.5"></marker>
<marker [lat]="54" [lng]="8.5"></marker>
</layer>
<layer [name]="'heatmapLayer'">
<heatmap></heatmap>
</layer>
</map-builder>
在LayerComponent
我有变量layer
和source
。在ngOnInit()
中,我设置了两个值。现在我需要访问嵌套组件中的两个值(Marker
和Heatmap
)。我试图在LayerComponent
中注入constructor()
,但我无法访问其变量。
感谢您的帮助!
答案 0 :(得分:1)
使用Input
装饰器并确保layer
中的source
和LayerComponent
属性公开:
export class MarkerComponent implements OnInit {
@Input() layer;
@Input() source;
}
export class HeatMapComponent implements OnInit {
@Input() layer;
@Input() source;
}
html:
<map-builder [width]="width">
<layer #lyr [name]="'markerLayer'">
<marker [layer]="lyr.layer" [scoure]="lyr.source" [lat]="8.5" [lng]="55.5"></marker>
<marker [layer]="lyr.layer" [scoure]="lyr.source" [lat]="54" [lng]="8.5"></marker>
</layer>
<layer #lyr2 [name]="'heatmapLayer'">
<heatmap [layer]="lyr2.layer" [scoure]="lyr2.source" ></heatmap>
</layer>
</map-builder>
或者在子项的consturctor中注入父项:
export class HeatMapComponent implements OnInit {
constructor(private layer : LayerComponent){}
ngOnInit(){
//this.layer.source
//this.layer.layer
this.layer.onDataChange.subscribe((data)=>{
console.log(data.layer,data.source)
})
}
在您的图层组件
中export class LayerComponent implements OnInit {
layer: any;
source: any;
@Output() onDataChange: EventEmitter<any> = new EventEmitter<any>();
someMethod() {
// when you change the value emit them
this.layer = someValue;
this.source = someValue;
this.onDataChange.emit({ layer: this.layer, source: this.source })
}
您获得了undefined
个值,因为您尝试在get initialized
<强> Demo 强>