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 a nested object that is null in Angular by utilizing ngFor

I am working on a situation where ngFor is being used to iterate through an array of objects that contain another object. <div *ngFor="item of items" > <div>{{item.item1}}</div> <input name="test" [(ngModel)]="{{item.item2.ite ...

Troubleshooting TypeScript compatibility with SystemJS when encountering problems with the .js extension

Initializing my TypeScript file with the import statement below. It's important to note that the lack of a .ts extension indicates that I am importing a TypeScript module: import githubService from './github.service'; Through transpilation ...

Can you explain the distinction between certain assignment assertion and ambient declaration?

When declaring that a field is definitely initialized within a class, what distinguishes the ! (exclamation point, definite assignment assertion) from the declare modifier? The subsequent code triggers an error in strict mode as TypeScript cannot confirm ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

The app deleted the Firebase database upon installation

I am currently developing an app to be launched on the Google Play Store that allows users to add data to Firebase, but not read it. Simultaneously, I have a second app which will remain private and won't be available on the Play Store. This app is u ...

Obtaining the response header in Angular 7 using flatMap

I am attempting to access the response header inside flatMap this.http.post<HttpResponse<any>>(`${environment.URL_API}/patients/v1/`, patient, {observe: 'response'}).pipe( flatMap((res: any) => { console.log(res) var loca ...

Sending information from the AppComponent to another component that is loaded at a separate time

Is there a way for me to maximize efficiency when fetching data from a service in the AppComponent and then passing it on to another component that's loaded later? I'd like to minimize API calls by reusing the same data in multiple places. How ca ...

When using `type B = A`, B is represented as A. However, if `type B = A | A` is utilized, B appears as 'any'. What causes this change in representation?

import { C } from "https://example.com/type.d.ts"; type D = C | C Playground Upon hovering over D in both the TS Playground and VS Code, it will show as C when declared as type D = C, but display any when declared as type D = C | C. Even if C&a ...

Using a custom validator in Angular that accepts an array as input

My special code: <input mdInput [mdAutocomplete]="auto" [(ngModel)]="formData.areaName" (keyup)="updateFilteredAreas(formData.areaName)" class="form-control {{areaName.errors ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

A helpful guide on showcasing error messages at the top of a form in Angular using reactive forms

I have a Validation summary component that is designed to fetch an ngForm, but it is currently unable to subscribe to status changes or value changes and display the summary of error messages. export class CustomValidationSummaryComponent implements OnIni ...

Approaches to evoke input onchange in Angular spec

How can I trigger the <input type="file"> onChange method in order to unit test the handleFileSelect function? When attempting to do so, I receive an error stating "imageInputNE.onchange is not a function". Here is the spec that I have written: ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Do I really need to install @angular/router as a dependency in Angular CLI even if I don't plan on using it?

After creating a new Angular CLI project, I noticed that certain dependencies in the package.json file seemed unnecessary. I wanted to remove them along with FormModules and HttpModules from imports: @angular/forms": "^4.0.0", @angular/http": "^4.0.0", @a ...

Prepare fixtures for commands in Cypress before executing the hook

One of my main tasks is to load the fixtures file only once and ensure it is accessible across all project files. To achieve this, I created a fixtures.js file with the following content: let fixturesData; export const loadFixturesData = () => { cy ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

How can you ensure an interface in typescript 3.0 "implements" all keys of an enum?

Imagine I have an enum called E { A = "a", B = "b"}. I want to enforce that certain interfaces or types (for clarity, let's focus on interfaces) include all the keys of E. However, I also need to specify a separate type for each field. Therefore, usi ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Dynamic property Key in TypeScript

Imagine receiving data from a search engine in the following format: const resultDe = { details_de: "Ein paar Informationen", foo_de:{bar:"barDe"}, code: "1C60" } const resultEn = { details_en: "Some information", fo ...