Connecting the SelectedItem of a listbox in ngPrime to an Observable Collection in Angular2

I am facing an issue while trying to use the ngPrime listbox in Angular2. I have a scenario where I am fetching an array of objects from Firebase as an observable and attempting to display it correctly in the listbox.

<div *ngIf="addContactDialogVisible==true">
<h3>Pick Contact</h3>
<p-listbox [options]="contactService.contacts|async"
           [style]="{'width':'250px','max-height':'250px'}">
  <template let-c>
    <div class="ui-helper-clearfix">
      <avatar-component [key]="c.$key" [avatarSize]="50"
                        style="display:inline-block;margin:5px 0 0 5px"></avatar-component>
      <div style="font-size:15px;float:right;margin:15px 10px 0 0">{{c.name}} {{c.surname}}</div>
    </div>
  </template>
  <button pButton type="text" (click)="send()" icon="fa-check" label="Upload"></button>
</p-listbox>

The challenge here is that contactService.contacts needs to be in ngPrime SelectItem[] format, causing all items to be selected. Additionally, the SelectItem object has a specific structure like {label:'New York', value:'New York'}, which my data does not conform to. How can I resolve this issue?

component.ts:

import {Component, OnInit, ChangeDetectorRef} from '@angular/core';
import {CalendarService} from '../common/services/calendar.service';
import {SimplyCalendarModel} from './calendar.model';
import {ContactService} from '../common/services/contact.service';
import {ContactWithKey} from '../contacts/models/contact.model';
import {SelectItem} from '../../../assets/primeng/components/common/api';
@Component({
  selector: 'calendar-component',
  template: require('./calendar.component.html'),
})

export class CalendarComponent implements OnInit {

 // con: SelectItem[];

  header: any;
  addContactDialogVisible: boolean = false;
  pickContact: ContactWithKey;

  constructor(
              private cd: ChangeDetectorRef,
              private contactService: ContactService) {
  }

  ngOnInit() {
    this.contactService.getContacts();

    this.header = {
      left: 'prev,next today',
      center: 'title',
      right: 'month,agendaWeek,agendaDay'
    };
  }

  handleDayClick(e) {
    this.addContactDialogVisible=true;
    this.cd.detectChanges();
  }

}

service:

public contacts: FirebaseListObservable<ContactWithKey[]>;

  constructor(private af: AngularFire) {
  }

  getContacts() {
    this.contacts = this.af.database.list('data/contacts');
    this.af.database.list('data/contacts')
      .subscribe(data => console.log(data));
  }

Answer №1

If you're looking to kick things off, here's a helpful guide for you. Start off by declaring your contacts variable within the component and populate it with data from your service. Your template HTML can then subscribe to contacts and retrieve the necessary data. Here are the steps you need to follow.

In calendar.component.html, make this adjustment:

<p-listbox [options]="contactService.contacts|async"
  [style]="{'width':'250px','max-height':'250px'}">

change it to:

<p-listbox [options]="contacts | async"
  [style]="{'width':'250px','max-height':'250px'}">

In calendar.component.ts, update this piece of code:

header: any;

to:

header: any;
contacts: FirebaseListObservable<ContactWithKey[]>;

NOTE: Make sure to import FirebaseListObservable at the beginning of calendar.component.ts

Finally, revise calendar.service.ts as follows:

getContacts() {
  return this.af.database.list('data/contacts');
}

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

Exploring the world of Typescript TSX with the power of generic

Introducing JSX syntax support in Typescript opens up new possibilities. I have an expression that functions smoothly with traditional *.ts files, but encounters issues with *.tsx files: const f = <T1>(arg1: T1) => <T2>(arg2: T2) => { ...

Error in React Native Navigation: Passing parameters is not functioning properly

Within my React Native application, I have meticulously established the following routes in my app.js: export default class App extends Component { render() { return ( <NavigationContainer> <Stack.Navigator initialRouteName=&qu ...

The benefits of exporting a component from one module and using it in another module

After putting in long hours trying to figure this out on my own, I've finally decided to seek help from the community. Thank you in advance for any assistance! I have a Web Projects Module that utilizes a Webpage Component. Within the Webprojects Mod ...

When importing a module, the function in the ts file may not be recognized or located

While attempting to create a VSTS (Azure Devops) Extension, I encountered a perplexing issue. Within my HTML page, I have a button element with an onclick listener: <!DOCTYPE html> <head> <script type="text/javascript"> VS ...

Issues regarding ambient getters and setters

Recently, I encountered an issue with my open-source library called Firemodel. The library utilizes ES classes and getters/setters within those classes. Everything was working smoothly until my VueJS frontend code started flagging every instance of these g ...

Navigating with hashtags in Angular2 and anchors does not change the page position

I recently came across a helpful post that showed me how to append a fragment to the URL. Angular2 Routing with Hashtag to page anchor Although the fragment is successfully added, I'm encountering an issue where the page does not scroll to the speci ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...

Stop /Terminate the Angular 2 HTTP API request

Occasionally, the loading time for an http API call can be quite lengthy. However, even if we navigate to another component, the call still continues execution (which is visible in the browser console). Is there a method or approach that allows us to can ...

What is the command to determine the version of TypeScript being used in the command line interface (CLI)?

I recently added TypeScript 1.7.4 using Visual Studio 2015, and it appears correctly installed within the IDE. However, when I check the version using tsc --version in the command line, it shows a different, older version - 1.0.3.0 instead of 1.7.4. Is t ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Having trouble utilizing the Visual Studio Code debugger in an Express.js project that uses TypeScript

My package.json file is shown below: ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev" ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Tips for conducting tests on an Observable<boolean>

I am facing an issue with handling an Observable in my code. Here is a snippet of the relevant parts: app.component.ts import { Observable } from "rxjs"; export class ProductComponent implements OnInit { ProductListLength: Num ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

When attempting to open an Angular modal window that contains a Radio Button group, an error may occur with the message "ExpressionChanged

I am brand new to Angular and have been trying to grasp the concept of lifecycle hooks, but it seems like I'm missing something. In my current project, there is a Radio Button Group nested inside a modal window. This modal is triggered by a button cl ...

issue with mat-select in a dialog not functionering correctly

In my current project, I am working on implementing a feature that requires the user to select an option from a drop-down menu and confirm their choice by clicking an "OK" button. To achieve this functionality, I am utilizing Angular Material. However, I h ...

There was an issue with loading resources in ASP.NET MVC with Angular 2 as the server responded with a 404 (Not Found) error

Encountering some unexpected behavior with typescript imports in ASP.Net MVC using Angular 2. The issue arises when the code errors at runtime stating it cannot locate the ng2-highcharts package from the root directory, rather than within node_modules. Al ...