重写后的标题为:将数据从模板传递给相关组件,而不是传递给其他组件
P粉464208937
P粉464208937 2023-09-10 15:17:04
0
1
402

如何将模板数据传递给相关组件,而不是传递给子组件或父组件,而不创建新的组件?

我的项目.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粉464208937
P粉464208937

全部回复(1)
P粉555682718

一种常见的方法是通过一个中间服务使用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();
      }
    }

不要忘记在消费者组件销毁时取消订阅,否则会导致内存泄漏。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!