Home  >  Q&A  >  body text

The rewritten title is: Pass data from template to related component, not to other components

How to pass template data to related components instead of child or parent components without creating new components?

My project.html

<div *ngFor="let item of items">
 <div *ngFor="let subItem of subItems">
  <div *ngIf="!item.value.length">
   <div class="cloth {{nextAvailableSubItem}}"></div>
  </div>
 </div>
</div>

my-item.component.ts

this.items = {one: ['redShirt'], two: [], three: [] four: ['whiteShirt', 'blackShirt']}
 this.subItems = ['redShirt', 'blueShirt', 'whiteShirt', 'blackShirt'];

filterItems(item, subItem){
 return nextAvailableSubItem //在redShirt之后应该返回whiteShirt以在模板中使用该值
    }
P粉464208937P粉464208937380 days ago486

reply all(1)I'll reply

  • P粉555682718

    P粉5556827182023-09-11 10:09:44

    A common approach is to use Observable to share data through an intermediate service

    As follows

    • Intermediate service:
    import { Injectable } from '@angular/core';
        import { BehaviorSubject, Observable } from 'rxjs';
        
        @Injectable({
          providedIn: 'root'
        })
        export class SharedDataService {
          private dataSource = new BehaviorSubject<any>('初始值');
          public data$: Observable<any> = this.dataSource.asObservable();
        
          updateData(newData: any): void {
            this.dataSource.next(newData);
          }
        }
    • First component (data sender):
    import { Component } from '@angular/core';
    import { SharedDataService } from './shared-data.service';
    
    @Component({
      selector: 'app-first-component',
      template: `...`
    })
    export class FirstComponent {
      constructor(private sharedDataService: SharedDataService) {}
    
      updateSharedData(): void {
        this.sharedDataService.updateData('新值');
      }
    }
    • Second component (data consumer):
    import { Component, OnDestroy } from '@angular/core';
        import { SharedDataService } from './shared-data.service';
        import { Subscription } from 'rxjs';
        
        @Component({
          selector: 'app-second-component',
          template: `...`
        })
        export class SecondComponent implements OnDestroy {
          sharedData: any;
          private subscription: Subscription;
        
          constructor(private sharedDataService: SharedDataService) {
            this.subscription = this.sharedDataService.data$.subscribe(data => {
              this.sharedData = data;
              // 在这里消费数据
            });
          }
        
          ngOnDestroy(): void {
            this.subscription.unsubscribe();
          }
        }

    Don't forget to unsubscribe when the consumer component is destroyed, otherwise it will cause a memory leak.

    reply
    0
  • Cancelreply