Bidirectional data binding in Angular 2: Establishing seamless communication between components through a

I am facing an issue where I want to pass an object from a component to a service and then fetch it in another component as an observable. The idea is that any changes made in the Question Component should automatically update the Service. However, at present, the getQuestion() method is not functioning properly for the Question Component.

Service:

   selectedSurvey: any;
   setQuestion(passedObject){ 
   this.selectedSurvey=  passedObject;
   }

   getQuestion(): Observable<any>{
  return this.selectedSurvey;
  }

Survey Component

   private subscription: Subscription;
   survey: any;
  onChange(surveyObject) {
    this.surveyService.setQuestion(surveyObject);

  }

  ngOnInit() {
   this.subscription =  this.surveyService.getSurveys().subscribe( survey => {  this.survey = survey });

  }

Survey Component Html

<div class="container">
    <div class="form-group">
        <label for="sel1">Select Survey:</label>
        <select class="form-control" [(ngModel)]="selectedObject" id="selsurvey" (ngModelChange)="onChange($event)">
          <option *ngFor="let s of survey" [value]="s">{{s.surveyName}}</option>

        </select>
      </div>
</div>

Question Component

  private subscription: Subscription;
    survey: any;
   constructor(private surveyService: SurveyService) { }

     ngOnInit() {
       this.subscription =  this.surveyService.getQuestion().subscribe( survey => { console.log(survey),this.survey = survey })
      }
}

Answer №1

During operation:

specificSubject:SpecificType<AnyTypeYouChoose>=new SpecificType<AnyTypeYouChoose>();

within the provider

operation.specificSubject.next(value);

within the recipient

  operation.specificSubject.subscribe(val=>{handler});

Answer №2

Take a look at this live demonstration: https://stackblitz.com/edit/angular-3anuot.

Examine the following files for details:

child-component/child-component.ts
,
child-component/communication.service.ts
, and app.component.ts.

Hopefully this information proves useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Each component does not have access to the same instance of a service

Objective: My goal is to develop a service with a subscribable array (BehaviorSubject) that updates client components whenever the data in the service changes. Initially, I plan to maintain a list of items on the server when new entries are added or modifi ...

Tips for accessing and modifying local files in Angular 2

Is there a method in Angular 2 to access files from an absolute path? I have utilized the 'filesaver' library for file saving, storing the files locally in txt/json formats. For instance: let blob = new Blob([document.getElementById(&apos ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

How can the carousel item numbers be adjusted for proper display?

I'm currently working on an Angular app and have encountered a task related to displaying 5 cards using mdbootstrap. I want to showcase these cards in a carousel format, but with a twist - I only want the carousel functionality to be active on mobile ...

Using Typescript alongside Angular 1.6 and browserify for your development needs

Currently navigating the world of working with Angular types in TypeScript and bundling code using Browserify. After following a TypeScript guide related to Gulp, I utilized npm to install the Angular types and put together this simple ts file. import * a ...

The event triggered by the tinymce editor does not immediately refresh the Angular Component

I am currently working on creating an Angular application using a WordPress instance of TinyMCE. Within the editor, there are non-content-editable elements that trigger a modal window to open when clicked. However, I have encountered an issue where the mo ...

Unique Version: When utilizing custom window.FileReader methods, Angular zone execution is bypass

Upon transitioning an Ionic/Angular project from Cordova to Capacitor, I found it necessary to override the default window.FileReader in order to successfully execute the onload() method. Here is the approach I took (https://github.com/ionic-team/capacitor ...

Develop dynamic components in Angular using up-to-date methods

I currently have three components named PersonComponent, AddressComponent, and CompanyComponent all already defined. Is there a way to dynamically create each component when I have the component name as text, for example, "PersonComponent"? I have inject ...

Personalize the appearance of autocomplete in Angular 2 using a dynamic <ng-content> tag

Currently, I am working on developing an autocomplete feature for a component. However, I am facing difficulties in handling the display of the items. I experimented with using ng-content to render the item but encountered failures. What I aim for is to ut ...

Tips for configuring the node_modules/lib path in an AngularJS project

I have been trying to see if the image is working properly. Is there a way to utilize global libraries for node_module? The installation seems to be in the correct place - c:\user\AppData\Roaming\npm\node_modules However, I a ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

Navigating API data conversion on the frontend using Object-Oriented Programming

Currently, I am facing a challenge while developing the frontend of a web application using TypeScript. The dilemma revolves around efficiently converting a data object from an API response into a format suitable for the application. Let's consider r ...

What is the definition of an interface when it comes to having certain guaranteed characteristics?

My current task involves interacting with an API that provides a list of images structured as follows: { "photos": { "1": "PHOTOS/1.jpg", "3": "PHOTOS/3.jpg", "4": "PHOTOS/4.jpg", "primary": "PHOTOS/X/PRI.jpg" }, "sketches": { "1 ...

Having trouble with Angular redirecting to the incorrect URL?

Currently delving into the world of Angular, I am eager to create a straightforward application where users can effortlessly switch between two components. The issue arises when attempting to navigate back from the navbar to the login component: <a rout ...

TypeScript Conditional type failing to detect conditional parameter

I am in need of a simple function that can return either a type "Person" or a type "PersonWithSurname". I have successfully implemented this using a conditional type. However, I am facing difficulties in structuring the result without encountering TypeScri ...

Creating a Schema for an Inclusive Array Type in JsonSchema

Imagine you have the following type: type oneOfTwoPossibleArrays = | [1, 2] | [3, 4] If you were to create a schema for it, what would it look like? This is my initial attempt that didn't work as expected: <Edit: this code works with aj ...

Tips for creating a unit test case for a specialized validator in angular reactive forms

Looking for guidance on creating a test case for this specific method: export class CustomErrorStateMatcher implements ErrorStatematcher { isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){ return control && control.inval ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Function in Typescript that accepts an extended interface as a parameter

I am facing an issue with my interface named "Example" which has a function type called "exampleFunction". The problem arises when this function takes a super class as an input parameter because TypeScript is reporting an error. It states that I cannot use ...