【问题标题】:Communication between 2 instances of the same ng component同一ng组件的2个实例之间的通信
【发布时间】:2020-11-04 14:00:45
【问题描述】:

在 Razor 视图中,我有一个角度组件:

<my-widget id="myWidget" isfullscreen="false" class="some-class"></my-widget>

当用户单击“弹出”按钮时,会在 iframe 中打开一个弹出窗口,我调用相同的组件但具有不同的属性值:

<my-widget id="myWidget" isfullscreen="true" class="some-class"></my-widget>

这意味着我有 2 个相同组件的不同实例。现在,在该组件中,我有一些输入、下拉列表等,并且在弹出窗口中,我希望它们处于与打开弹出窗口之前相同的状态。这意味着如果用户更改下拉列表中的值,并且他单击“弹出”按钮,我不希望选择下拉列表的默认值。相反,我想要的是他在点击按钮之前选择的那个。

我设法用全局变量做到了这一点。在下拉列表的更改事件中,我将全局变量设置为正确的值。在组件的 init 事件中,我检查全局变量是否存在,如果存在,我会使用它。我不喜欢这种方法。还有其他方法吗?

【问题讨论】:

  • 只是为了确保我理解你的结构,这两个组件不是父子,它们完全不相关,对吧? (即使是相同的组件代码)
  • 是的,没错,它们是不相关的。 @Technoh

标签: jquery angular angular10


【解决方案1】:

对于两个不相关的组件之间的通信,发送数据的唯一方法是通过使用服务。我们经常想到服务用于获取远程数据,但它们也用于在应用程序的组件之间共享数据。如果还不是这样,您将需要熟悉服务以及可观察对象和主题/行为主题。这是以这种方式使用服务的一种方式,来自fireship.io

data-sharing.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataSharingService {

  private currentData$ = new BehaviorSubject(0); // change the value to the default value for the dropdown

  constructor() { }

  updateData(data: number) { // change this as well depending on data
    this.currentData$.next(data);
    return this.currentData$;
  }
}

组件.ts

import { Component, OnInit } from '@angular/core';
import { DataSharingService } from "../data-sharing.service";

@Component({
  selector: 'app-component',
  template: 'app-component,
  styleUrls: ['./your.component.css']
})

export class ParentComponent implements OnInit {    
  dropDownValue: number; // change this depending on your dropdown value

  constructor(private dataSharingService: DataSharingService) { }

  ngOnInit() {
    this.dataSharingService.currentData$.subscribe(newData => this.dropDownValue = newData)
  }

  updateValue(event) {
    this.dataSharingService.updateData(event.target.value);
  }
}

component.html

<select id="[...]" name="[...]" [(ngModel)]="[...]" (change)="updateValue($event)">
  <option *ngFor="let [...]" [ngValue]="[...]">[...]</option>
</select>

我使用了很多 [...],因为我不知道您如何渲染组件,甚至不知道您使用的是表单还是响应式表单。

【讨论】:

    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 2019-10-10
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2015-04-07
    相关资源
    最近更新 更多