【问题标题】:Angular 6 communicate between 2 components instances through serviceAngular 6 通过服务在 2 个组件实例之间进行通信
【发布时间】:2019-10-10 06:26:32
【问题描述】:

我有一个组件通过调用服务来动态加载/删除另一个组件。 我还让动态添加组件能够自行删除。我的问题是通知其他组件动态组件的这个实例已被删除。

我尝试使用事件输出/发出和主题/订阅,但没有运气。不知道是不是我做错了。

这是我的代码,一旦单击按钮并添加了组件,如果我使用组件内的关闭按钮,主按钮不知道这一点,它需要单击 2 次才能向右切换,加上文本按钮会出错

https://stackblitz.com/edit/dynamically-row-components-for-smart-table

我在使用主题并订阅时遇到的问题,它会在所有实例中触发而不影响按钮!

【问题讨论】:

    标签: angular typescript binding angular-dynamic-components


    【解决方案1】:

    您可以做一些事情来使其工作,而不是为所有组件订阅一个公共主题或事件发射器,而是为每个组件动态创建一个独特的主题。所以它不会为所有组件触发。首先,您需要为每个组件提供一个唯一的 componentName,或者您可以使用 id。

    data = [
        {
          id: 1,
          name: 'Leanne Graham',
          username: 'Bret',
          email: 'Sincere@april.biz',
          button: 'Button #1',
          componentName:"component"+1
        }
    

    第 2 步:根据 componentNae 为每行创建注册主题。每次关闭点击相应的订阅将调用,然后你可以从这里删除组件

        ngOnInit() {
            this.renderValue = this.value.toString().toUpperCase();
             this.InjiService.componentSubjects[this.rowData.componentName] = new Subject();
             this.InjiService.componentSubjects[this.rowData.componentName].subscribe(()=>{
    
              this.InjiService.removeComponent(this.expanededComp);
              this.expanededComp = null;
              //this.renderValue = this.value.toString().toUpperCase(); //"Open";
              this.isOpen = false;
              //firing the change detection manually
              this.ref.markForCheck();    
            });
    
      }
    

    请确保在您的服务中声明了 componentSubjects

    export class InjiService {
     public componentSubjects: { [name: string]: Subject<any> } = {};
    

    Working sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-07
      • 2019-03-24
      • 1970-01-01
      • 2010-09-29
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多