我正在尝试学习角度2,并尝试使用来自子组件的数据在父组件中设置变量。基本上我在父视图中有一个子标题,我希望标题和一些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>
对于我的生活,我无法使用这种方法,并且无法确定我出错的地方。我总是可以把子标题放在我的孩子身上,但我不喜欢重复代码这么多次的想法,这会让我的布局更难实现。
答案 0 :(得分:1)
最好的方法是使用服务和observable
,以便每当子组件发生更改时,新数据将立即反映在父组件中。
在你的service.ts,
import { Subject } from 'rxjs/Subject'
import { Observable } from 'rxjs/Rx';
@Injectable()
export class myService {
private pageName = new Subject<string>();
pageNameChange$ = this.pageName.asObservable();
changedComponentName(option:string){
this.pageName.next(option);
}
}
在您的子组件中,
子组件1
public ngOnInit() {
this.myService.changedComponentName('child1');
}
子组件2
public ngOnInit() {
this.myService.changedComponentName('child2');
}
依旧......
现在,要在父组件中获取更改的组件名称,
parent component.ts
import { Subscription } from 'rxjs';
export class parentComponent {
private subscription:Subscription;
constructor(private myService:myService){
this.myService.pageNameChange$.subscribe( /* get called on every child page changes*/
newPageName => {
console.log(newPageName); // you get your passed component name ( child1 / child2 /etc.. here in the 'newPageName' variable
});
}
}
答案 1 :(得分:0)
$event
?
如果是,那么为什么在父类方法中使用let childDetails ={}
?相反,您应该使用this.childDetails={}
onChildLoaded($event){
this.childDetails ={ title: $event.childTitle, helperBar: $event.childHelperBar };
console.log (childDetails);
}
和父母的HTML
<div class="subheader"> <h1>{{ childDetails.title }}</h1> {{ childDetails.helperBar }} </div>
<nav class="sidebar"> </nav>
<main role="main" class="">
<app-first-child (childLoaded)="onChildLoaded($event)"></app-first-child> </main>
如果您不想使用<app-first-child/>
,那么您应该使用共享服务