【问题标题】:Sharing Date Value from one component to another component in angular?以角度将日期值从一个组件共享到另一个组件?
【发布时间】:2021-07-07 01:39:53
【问题描述】:

我正在尝试以角度在组件之间共享 日期

  1. 我的组件没有关系。所以@Input 和@Output 的所有方法都不起作用。
  2. 如上所述,我的组件是不相关的,所以你会说“try behaviorSubject”......我有!
  3. 我正在使用 devextreme 角度形式。
  4. 我使用的是 Angular 版本 10。

现在的场景是 我在用户选择日期的一个组件中有 ANGULAR FORM。提交时调用服务并在网格中显示数据。 我需要将用户在第一个组件的表单中选择的确切 日期 放在第二个组件的日期选择字段中。

请帮帮我!

【问题讨论】:

  • 行为主题非常适合组件不相关的情况,我看不出它如何解决您的问题。只需确保一个组件正在更新它,而另一个组件订阅了更改。
  • "所以,你会说“try behaviorSubject”......我有!” - 你是在哪里以及如何尝试的? BehaviorSubject 必须在两个组件都可以访问的单例服务中。

标签: angular angular-components


【解决方案1】:

您可以为此目的使用服务和主题或行为主题。

点击文档链接。
https://angular.io/guide/component-interaction#parent-and-children-communicate-using-a-service

【讨论】:

    【解决方案2】:

    在不相关的组件之间传递数据时,RxJS BehaviorSubject 似乎非常有用。因此,从第一个组件到第二个组件共享日期值可能会对您有所帮助:

    date.service.ts

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable()
    export class DateService {
    
      private dateSource = new BehaviorSubject<any>(new Date().toLocaleDateString());
      currentDate = this.dateSource.asObservable();
    
      constructor() { }
    
      changeDate(date: any) {
        this.dateSource.next(date)
      }
    }
    

    second.component.ts

    import { Component, OnInit } from '@angular/core';
    import { DateService } from "../date.service";
    
    @Component({
      selector: 'app-second',
      template: `
         {{date}}
       `,
       styleUrls: ['./second.component.css']
    })
    
    export class SecondComponent implements OnInit {
    
      date: any;
    
      constructor(private dateService: DateService) { }
    
      ngOnInit() {
        this.dateService.currentDate.subscribe(date=> this.date = date)
      }
    }
    

    first.component.ts

    import { Component, OnInit } from '@angular/core';
    import { DateService } from "../date.service";
    
    @Component({
      selector: 'app-first',
      template: `
        {{date}}
        <button (click)="newDate()">New Date</button>
      `,
      styleUrls: ['./first.component.css']
    })
    
    export class FirstComponent implements OnInit {
    
      date: any;
    
      constructor(private dateService: DateService) { }
    
      ngOnInit() {
      }
    
      newDate() {
        this.dateService.changeDate(date);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 2019-08-03
      • 2022-11-04
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2018-04-24
      相关资源
      最近更新 更多