Angularで親子関係でないコンポーネント間で変数を共有したい

実現したいこと・前提

Angularで親子関係でないコンポーネント間で変数を共有したいです。

具体的には検索条件のコンポーネントと検索ボタンを置いているコンポーネントを別々で作成しています。
検索ボタンのコンポーネントから「検索」ボタンを押したとき、検索条件のコンポーネントの値を取得したいです。
現状はデフォルトのテキストを変更したときに取得した値がデフォルトのままになっています。

そもそもの書き方が違うのでしょうか?Angularにおいて、親子関係にないコンポーネント間で値を受け渡す方法を教えていただきたいです。

アプリ全体のテンプレート

app.component.html

1<app-condition></app-condition> 2<app-search></app-search>

データサービス

data.service.ts

1import { Injectable } from '@angular/core'; 2import { BehaviorSubject } from 'rxjs'; 3@Injectable({ 4 providedIn: 'root' 5}) 6export class DataService { 7 condition!: BehaviorSubject<string>; 8 constructor() { } 9 10 getCondition(): string { 11 return this.condition.getValue(); 12 } 13}

検索条件のコンポーネント

condition.component.ts

1import { Component, OnInit } from '@angular/core'; 2import { DataService } from '../data.service'; 3import { BehaviorSubject } from 'rxjs'; 4 5@Component({ 6 selector: 'app-condition', 7 templateUrl: './condition.component.html', 8 styleUrls: ['./condition.component.css'] 9}) 10export class ConditionComponent implements OnInit{ 11 condition: string = '検索文字列'; 12 13 constructor(private dataService: dataService) { } 14 15 ngOnInit() { 16 this.dataService.condition = new BehaviorSubject(this.condition); 17 } 18}

condition.component.html

1<input type="text" [(ngModel)]="condition" placeholder="検索文字列">

検索ボタンコンポーネント

search.component.ts

1import { Component } from '@angular/core'; 2import { DataService } from '../data.service'; 3 4@Component({ 5 selector: 'app-search', 6 templateUrl: './search.component.html', 7 styleUrls: ['./search.component.css'] 8}) 9export class SearchComponent { 10 constructor(private dataService: DataService) { } 11 12 search(): void { 13 console.log(this.dataService.getCondition()); // 最終的にここにinputタグ内の文字列が取れるようにしたい 14 } 15}

search.html

1 <button (click)="search()">検索</button>

補足情報(FW/ツールのバージョンなど)

Angularのバージョンは16です。

コメントを投稿

0 コメント