搜尋

首頁  >  問答  >  主體

重寫後的標題為:將資料從範本傳遞給相關元件,而不是傳遞給其他元件

如何將範本資料傳遞給相關元件,而不是傳遞給子元件或父元件,而不建立新的元件?

我的專案.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粉464208937444 天前527

全部回覆(1)我來回復

  • P粉555682718

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

    一種常見的方法是透過一個中間服務使用Observable來共享資料

    如下圖

    • 中間服務:
    #
    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);
          }
        }
    • 第一個元件(資料傳送者):
    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('新值');
      }
    }
    • 第二個元件(資料消費者):
    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();
          }
        }

    不要忘記在消費者元件銷毀時取消訂閱,否則會導致記憶體洩漏。

    回覆
    0
  • 取消回覆