我有两个组件-一个mainComponent,一个MenuComponent。 从MenuComponent,我想更改mainComponent中的变量。
import { Injectable, Component, OnInit, NgZone } from '@angular/core';
@Injectable()
@Component({
selector: 'app-componentmain',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class ComponentMainContent {
public selectedGroup : any;
在菜单组件中:
import { ComponentMainContent } from '../main/main.component';
@Component({
..
providers: [ComponentMainContent]
..
export class MenuListItemComponent implements OnInit {
constructor(private ComponentMain: ComponentMainContent,
..
showGroup(item: NavItem){
this.ComponentMain.selectedGroup = 'test'; - nothing is happening
}
在主要component.html中:
{{selectedQmgr}}
你能告诉我我想念的东西吗? 谢谢!
答案 0 :(得分:1)
我认为有几种方法可以解决此问题。尽管您认为应该可以将父组件注入到子组件中,但是我并没有使用您尝试的方法太多,因此我无法对可能发生的事情发表任何评论。我使用的其他两种方法是:
编辑:由于穆罕默德已经发布了共享服务的示例,因此添加了EventEmitter选项的示例。
@Component({
selector: 'menu-item-component',
... // omitted properties
})
export class MenuItemComponent {
@Output() groupSelected: EventEmitter<string> = new EventEmitter<string>();
constructor() {}
showGroup(item: NavItem){
//this.ComponentMain.selectedGroup = 'test'; - nothing is happening
this.groupSelected.emit('test'); //Emit whatever value you want here.
}
}
现在在您的html模板文件中的某个位置的主要组件中(这假定菜单项是直接子项):
<menu-item-component (groupSelected)="callbackFunction($event)">Sample</menu-item-component>
callbackFunction()将是您主要组件上的一个函数,该函数将传递菜单项发出的值。
@Component({
selector: 'main-component',
... // omitted properties
})
export class MainComponent {
selectedGroup: string = null;
constructor() {}
callbackFunction(group: string) {
//Do something with the value here.
this.selectedGroup = group;
}
}
答案 1 :(得分:1)
只需创建一个共享服务,然后将该服务注入组件中,然后您就可以更改该服务的任何属性,因为它是同一服务,因此会反映到其他组件中。
@Injectable({
providedIn:'root'
})
export class DataService {
private currentValue : number = 0;
update() {
this.currentValue++;
}
get selectedValue(){
return this.currentValue
}
}