Angular - 如何从另一个组件切换组件中元素的可见性?

Leo*_*ati 1 javascript angular-components angular

我的 Angular 应用程序中有以下场景:

MainDashboardComponent当我有 route 时可见的组件/。显然我的文件中有<router-outlet>标签app.component.html,它看起来像这样:

<app-side-menu></app-side-menu>
<div class="main-container">
  <div class="content">
    <router-outlet></router-outlet>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我有一个SideMenuComponent我用来在我的所有路线上都有一个侧面菜单。在MainDashboardComponent我有一个方法,由于某种原因需要切换位于侧边菜单上的聊天元素。在SideMenuComponent我内部有一个处理聊天元素可见性切换的方法,它按预期工作。如何从我的调用此方法MainDashboardComponent并从那里切换聊天元素?

我尝试过但没有成功

我试图注入SideMenuComponent我的内部MainDashboardComponent,但是虽然toggleChat()调用了该方法,但该元素并没有改变它的可见性。看起来我有一种相同组件的多个实例,我猜...

你能帮我解决这个问题吗?谢谢!

主仪表板组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-main-dashboard',
  templateUrl: './main-dashboard.component.html',
  styleUrls: ['./main-dashboard.component.scss']
})
export class MainDashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {}

  setFocus(id) {
    // here I'd like to call SideMenuComponent togglechat() ... 
  }
}
Run Code Online (Sandbox Code Playgroud)

侧边菜单组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-side-menu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.scss']
})
export class SideMenuComponent implements OnInit {

  showChat: boolean;

  constructor() {
    this.showChat = false;
  }

  ngOnInit() {
  }

  toggleChat() {
    this.showChat = !this.showChat;
  }

}
Run Code Online (Sandbox Code Playgroud)

Sar*_*wal 6

要在不同的组件之间进行通信,有不同的方式。

  • 如果要在父子组件之间进行通信,可以使用EventEmitter从子组件发出事件并在父组件中处理事件
  • 如果你想在任何组件之间进行通信,你可以使用Service并借助EventEmitterSubject/BehaviorSubject来实现通信

在您的情况下,我们可以创建一个服务 myService.ts 并声明和 eventEmitter

.service.ts

@Injectable()
export class AppCommonService {

 toggle : EventEmitter<boolean> = new EventEmitter<boolean>()

}
Run Code Online (Sandbox Code Playgroud)

mainDashboard.component.ts

constructor(private myService : myService){}

chatStatus : boolean = false;
ngOnInit(){
 this.myService.toggle.subscribe(status=>this.chatStatus = status);
}

toggleChat(){
 this.myService.toggle.emit(!this.chatStatus);
}
Run Code Online (Sandbox Code Playgroud)

sideMenu.component.ts

constructor(private myService : myService){}

chatStatus : boolean = false;

ngOnInit(){
  this.myService.toggle.subscribe(status=>this.chatStatus = status);
}
Run Code Online (Sandbox Code Playgroud)