DEV Community

Cover image for how to use subject in angular
Angga Lesmana
Angga Lesmana

Posted on

how to use subject in angular

let's implement how to use subject in angular,
first we create 2 component , component1 and component2
this is such as share data among different component,
via Serrvice,

we will create simple input and share texInput to another component

first we create function in component1.ts

in component ts

 enteredText: string;
  clickFun(){
    console.log(this.enteredText)
  }

Enter fullscreen mode Exit fullscreen mode

in componenten1.html

<div class="container">
  <input type="text" [(ngModel)]="enteredText">
  <button (click)="clickFun()">click</button>
</div>

Enter fullscreen mode Exit fullscreen mode

Image description

in the top input text in comp1
and text comp2 work from component2

and now create component2


<div class="container">
  <p>
    comp2 works! {{inputText}}
  </p>
</div>

Enter fullscreen mode Exit fullscreen mode

and in component2 ts

  inputText : string

Enter fullscreen mode Exit fullscreen mode

and now create service for share data from input component1 into component2

datasubject = new Subject<string>();

 shareDataText(data: any) {
    this.datasubject.next(data.toString()); //
  }


Enter fullscreen mode Exit fullscreen mode

and dont forget for import Subject from rxjs
if we already create service
now we call the service in the app.module
exactly at providers: [NameService]

let call service in component1

  constructor(private dataservice: DataService) { }

Enter fullscreen mode Exit fullscreen mode

dont forget to import the service
and now we create call in our clickbutton function

 clickFun(){
    this.dataservice.shareDataText(this.enteredText)
  }
Enter fullscreen mode Exit fullscreen mode

and we call the service in component2

 ngOnInit() : void{
    this.dataservice.datasubject.subscribe(value => {
      this.inputText = value
    })
  }

Enter fullscreen mode Exit fullscreen mode

and we see when we click input button in component1
data will show in component2

Image description

Top comments (0)