DEV Community

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

Posted on

1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay