我正在尝试学习角度2,并且我正在尝试使用来自我的子组件的数据在父组件中设置变量 . 基本上我在父视图中有一个子 Headers ,我希望 Headers 和一些HTML根据加载的子项进行更改 .
父组件:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ParentComponent {
childDetails: {title: String, helperBar: String};
onChildLoaded(childData: {
childTitle: string,
childHelperBar: string
}) {
this.childDetails ={
title: childData.childTitle,
helperBar: childData.childHelperBar
};
console.log (childDetails);
}
}
子组件:
import { Component, OnInit, ViewEncapsulation, Output, EventEmitter }
from '@angular/core';
@Component({
selector: 'app-first-child',
templateUrl: './first-child.component.html',
styleUrls: ['./first-child.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class FirstChildComponent implements OnInit {
@Output() childLoaded = new EventEmitter<{childTitle: string,
childHelperBar: string}>();
constructor() { }
ngOnInit() {
this.childLoaded.emit({
childTitle: 'Dashboard',
childHelperBar: '<div class="test"><button>Dash Button</button>
</div>'
});
}
}
最后是我的父HTML:
<div class="subheader">
<h1>{{ childDetails.title }}</h1>
{{ childDetails.helperBar }}
</div>
<nav class="sidebar">
</nav>
<main role="main" class="">
<router-outlet (childLoaded)="onChildLoaded($event)"></router-outlet>
</main>
对于我的生活,我无法使用这种方法,也无法确定我哪里出错了 . 我总是可以把子 Headers 放在我的孩子身上,但我不喜欢重复代码这么多次的想法,这会让我的布局更难实现 .
2 回答
最好的方法是使用服务和
observable
,这样每当子组件发生更改时,新数据将立即反映在父组件中 .在你的service.ts,
在您的孩子组件中,
儿童组成部分1
儿童组成部分2
等等..
现在,要在父组件中获取更改的组件名称,
父组件.ts
你来了吗?
$event
在您的父方法中?如果是,那么为什么在父类方法中使用
let childDetails ={}
. 相反,你应该使用this.childDetails={}
和父母的HTML应该是
如果您不想使用
<app-first-child/>
,那么您应该使用共享服务