Material angular autocomplete keeps giving me error - angularjs

I am trying to make this demo work but somehow it is not working for me. It keeps giving me error
servers.component.ts
import { Component } from '#angular/core';
import {FormControl} from '#angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';
#Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class User {
constructor(public name: string) { }
}
export class ServersComponent {
myControl = new FormControl();
options = [
new User('Mary'),
new User('Shelley'),
new User('Igor')
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this.filter(name) : this.options.slice())
);
}
filter(name: string): User[] {
return this.options.filter(option =>
option.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
displayFn(user?: User): string | undefined {
return user ? user.name : undefined;
}
}
I have imported both User class and ServersComponent in app.module.ts.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AlertModule } from 'ngx-bootstrap';
import "hammerjs";
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {MatButtonModule, MatInputModule } from '#angular/material';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { ServerComponent } from './server/server.component';
import { ServersComponent, User } from './servers/servers.component';
import { MyFormComponent } from './my-form/my-form.component';
import {MatCheckboxModule} from '#angular/material/checkbox';
import {MatAutocompleteModule} from '#angular/material/autocomplete';
#NgModule({
declarations: [
AppComponent,
ServerComponent,
ServersComponent,
MyFormComponent,
User,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AlertModule.forRoot(),
FormsModule,
ReactiveFormsModule,
MatButtonModule,
MatInputModule,
MatCheckboxModule,
MatAutocompleteModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
However if i use this demo it is working fine.
Can you let me know what I am doing wrong in my code.

Problem lies in this line,
import { ServersComponent, User } from './servers/servers.component';
Usually you can have only one component from a select/component. Remove User from the same.
To add more on the issue, you should not export two classes from same component. change your component as,
import { Component } from '#angular/core';
import {FormControl} from '#angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';
#Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class ServersComponent {
myControl = new FormControl();
options = [
new User('Mary'),
new User('Shelley'),
new User('Igor')
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this.filter(name) : this.options.slice())
);
}
filter(name: string): User[] {
return this.options.filter(option =>
option.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
displayFn(user?: User): string | undefined {
return user ? user.name : undefined;
}
}

Related

Bootstrap undefined when trying to initialize a tool tip in angular-bootstrap

I'm looking to setup a couple of angular bootstrap tooltips per https://ng-bootstrap.github.io/#/components/tooltip/examples.
I have a component for a contact-form which has the following:
import { Component, OnInit, Injectable, NgModule } from '#angular/core';
import { FormGroup, FormControl, Validators, FormArray, ReactiveFormsModule } from '#angular/forms';
import { HttpClient } from '#angular/common/http';
import { ApiHttpService } from '../services/api-http.service';
import { Constants } from '../config/constants';
import { Observable, OperatorFunction } from 'rxjs';
import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';
import { FormsModule } from '#angular/forms';
import { JsonPipe } from '#angular/common';
import { NgbTypeaheadModule, NgbTooltip } from '#ng-bootstrap/ng-bootstrap';
declare var bootstrap: any
#Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css'],
// standalone: true,
// imports: [NgbTypeaheadModule, FormsModule, JsonPipe, ReactiveFormsModule, NgbTooltipModule],
})
#Injectable()
export class ContactFormComponent implements OnInit {
constructor(private http: HttpClient, private apiHttpService:ApiHttpService) {}
contactForm: FormGroup;
ngOnInit() {
this.contactForm = new FormGroup({
'requestorData': new FormGroup({
'name': new FormControl(null, Validators.required),
'item': new FormControl(null, Validators.required),
'supplier': new FormControl(null,Validators.required),
// 'contact': new FormControl(null,Validators.required),
'budget': new FormControl(null,Validators.required),
'confidential': new FormControl(false),
'pii': new FormControl(false),
'cloud': new FormControl(false),
'intData': new FormControl(false),
'entCritical': new FormControl(false),
})
});
this.getVendorData()
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
}
)
}
And then in my contact-form.html file (the bottom of the form)
<span *ngIf="!contactForm.valid && contactForm.touched" class="help-block">Please fill in all the required fields!</span>
<button [disabled]="!contactForm.valid" class="btn btn-primary" type="submit">Submit</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Tooltip on bottom">
Tooltip on bottom
</button>
The error I am getting in the browser is -
ERROR ReferenceError: bootstrap is not defined
at contact-form.component.ts:48:7
at Array.map (<anonymous>)
at ContactFormComponent.ngOnInit (contact-form.component.ts:47:42)
at callHook (core.mjs:2498:22)
at callHooks (core.mjs:2467:17)
at executeInitAndCheckHooks (core.mjs:2418:9)
at refreshView (core.mjs:11984:21)
at refreshComponent (core.mjs:13043:13)
at refreshChildComponents (core.mjs:11759:9)
at refreshView (core.mjs:12019:13)
Also, here is my app.ts which has the import
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { ContactFormComponent } from './contact-form/contact-form.component';
import { JumbotronComponent } from './jumbotron/jumbotron.component';
import { FooterComponent } from './footer/footer.component';
import { NgbTypeaheadModule, NgbTooltipModule } from '#ng-bootstrap/ng-bootstrap';
import { JsonPipe } from '#angular/common';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
#NgModule({
declarations: [
AppComponent,
ContactFormComponent,
JumbotronComponent,
FooterComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule,
NgbTypeaheadModule,
FormsModule,
JsonPipe,
NgbTooltipModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Am I missing something with how I am initializing the tooltip in my .ts file?
Thanks

How to send array object input to firestore on Angular?

I'm just learning angular and trying to make a to-do-list app. I'm trying to send array object data to firestore. I have an array object input like this:
[
{
"isChecked": true
"title": "Todo 1",
},
{
"isChecked": true,
"title": "Todo 2"
}
]
I want to enter that into the input field. And here is my input field:
<form action="" #importForm="ngForm (ngSubmit)="importJson(importForm, $event)">
<div class="form-group">
<textarea ngModel name="importjson" #importjson="ngModel" class="form-control" id="exampleFormControlTextarea1" rows="10" required></textarea>
</div>
<button type="submit" class="btn btn-secondary" >Ok</button>
</form>
And this is my app component :
import { Component, ViewChild, OnInit, ElementRef } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { FormGroup } from '#angular/forms';
import { TodolistService } from '../../services/todolist.service';
import { Todolist } from '../../model/todolist.model';
export class TodolistComponent implements OnInit {
importjson: Todolist={};
constructor(private todolistService: TodolistService) { }
#ViewChild('editTitle', {static: false}) input: ElementRef;
ngOnInit(): void{
this.todolistService.getToDoList().subscribe(items => {
this.todos = items;
})
}
importJson(importForm: FormGroup, submit){
console.log(importForm.value.importjson);
this.todolistService.addImport(importForm.value.importjson);
this.importState = false;
}
}
And here is my app service:
import { Injectable } from '#angular/core';
import { AngularFireDatabase, AngularFireList } from '#angular/fire/database' ;
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '#angular/fire/firestore';
import { Observable } from 'rxjs';
import { Todolist } from '../model/todolist.model';
#Injectable({
providedIn: 'root'
})
export class TodolistService {
itemsCollection: AngularFirestoreCollection<Todolist>;
items: Observable<Todolist[]>;
itemDoc: AngularFirestoreDocument<Todolist>;
constructor(private firebasedb: AngularFireDatabase, public firestore: AngularFirestore) {
this.itemsCollection = this.firestore.collection('titles');
this.items = this.itemsCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Todolist;
data.id = a.payload.doc.id;
return data;
}))
);
}
addImport(item: Todolist) {
this.itemsCollection.add(item);
}
How can I do that?

Trying to get a unique list of objects from an array in angular

Have an observable being returned from my service.ts as shown here:
import { Injectable, ErrorHandler } from '#angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from
'#angular/common/http'
import { Observable } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { PokeResponse } from '../PokeResponse';
#Injectable({
providedIn: 'root'
})
export class PokeApiService {
private url = "https://pokemon-go1.p.rapidapi.com/pokemon_stats.json";
constructor(private http:HttpClient) { }
getPokeData(): Observable<PokeResponse> {
return this.http.get<PokeResponse>(this.url,
{
headers : new HttpHeaders({
'x-rapidapi-key': 'a6cef4cbcamsh05b29346394d4a4p1bafacjsn2a92406ac103'
})
})
.pipe(
tap(data => console.log('Pokedata/Error' + JSON.stringify(data))
),
catchError(this.handleError)
);
}
private handleError(err:HttpErrorResponse) {
console.log('PokemonService: ' + err.message);
return Observable.throw(err.message);
}
}
This is my response:
export interface PokeResponse{
list:results[];
results:{
pokemon_id:number;
pokemon_name:string;
base_attack:number;
base_defense:number;
base_stamina:number;
}[];
}
export interface results{
pokemon_id:number;
pokemon_name:string;
base_attack:number;
base_defense:number;
base_stamina:number;
}
export class Pokemon implements results{
pokemon_id:number;
pokemon_name:string;
base_attack:number;
base_defense:number;
base_stamina:number;
constructor(_id:number, _name:string, _atk:number, _def:number, _stam:number) {
_id = this.pokemon_id;
_name = this.pokemon_name;
_atk = this.base_attack;
_def = this.base_defense;
_stam = this.base_stamina;
}
}
And this is my component.ts:
import { Component, OnInit } from '#angular/core';
import { PokeApiService } from 'src/app/services/poke-api.service';
import { PokeResponse, results, Pokemon } from 'src/app/PokeResponse';
import { Observable } from 'rxjs';
#Component({
selector: 'app-list-pokemon',
templateUrl: './list-pokemon.component.html',
styleUrls: ['./list-pokemon.component.css']
})
export class ListPokemonComponent implements OnInit {
constructor(private pokeService: PokeApiService) { }
ngOnInit(): void {
this.getPokeDetails();
}
pokeData:PokeResponse;
errorMessage:any;
pokeArray:results;
getPokeDetails() : boolean {
this.pokeService.getPokeData().subscribe(
pokeData => {
this.pokeData=pokeData;
console.table(pokeData);
},
error => this.errorMessage = <any>error
);
return false;
}
}
In my console I'm getting back a console.table of my observable like this
I'm trying to filter out the names of Pokemon which are the same as others, which could also be achieved by just filtering out any of the pokemon_ids as all the stats match regardless of the type.
So far I've tried:
console.log(this.pokeArray);,
using [...Set()], forEach(), and Array.from()
Any help or suggestions on how I can make this question any clearer would be greatly appreciated.
Try this, using filter:
// list-pokemon.component.ts
export class ListPokemonComponent implements OnInit {
uniqueListPoke = [];
flags = {};
constructor(private pokeService: PokeApiService) { }
ngOnInit(): void {
this.getPokeDetails();
}
pokeData:PokeResponse;
errorMessage:any;
pokeArray:results;
getPokeDetails() : boolean {
this.pokeService.getPokeData().subscribe(
pokeData => {
this.uniqueListPoke = pokeData.filter((entry) => {
if (this.flags[entry.pokemon_name]) {
// console.log('flags', false);
return false;
}
this.flags[entry.pokemon_name] = true;
return true;
});
console.log(JSON.stringify(this.uniqueListPoke));
},
error => this.errorMessage = <any>error
);
return false;
}
}
The working example:
https://stackblitz.com/edit/angular-distinct-poke?file=src/app/hello.component.ts

Trying to use select of #ngrx/store causes undefined variable

I have been following https://github.com/ngrx/example-app very closely while creating a project in Angular.
I'm trying to select a value from a root reducer in my component, and it is not working.
The component (and line) in question:
import { Component } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { Store } from '#ngrx/store';
import * as rootReducer from '../../reducer/';
import * as layoutActions from '../../actions/layout';
#Component({
selector: 'app-nav-bar',
template: `
<nav>
<div class="logo">
linkme
</div>
<a routerLink="/home">Home</a>
<a routerLink="/groups">Groups</a>
<div class="button" (click)="toggleAddModal()">add thing</div>
</nav>
<add-link-modal [open]="showAddModal$ | async"></add-link-modal>
`,
styleUrls: ['./nav-bar.component.scss']
})
export class NavBarComponent {
showAddModal$: Observable<boolean>;
constructor(private store : Store<rootReducer.State>) {
****** this.showAddModal$ = store.select(rootReducer.getShowAddModal); ****** this is the line that is breaking
}
toggleAddModal()
{
this.store.dispatch({type: layoutActions.TOGGLE_ADD_MODAL})
}
}
app.module.ts
...
import { Store, StoreModule } from '#ngrx/store';
import { reducers } from './reducer/'
import { AppComponent } from './app.component';
...
#NgModule({
...
imports: [
...
StoreModule.provideStore(reducers)
...
],
..
})
export class AppModule { }
reducers/index.ts
import { combineReducers } from '#ngrx/store';
import { createSelector } from 'reselect';
import { ActionReducer } from '#ngrx/store';
import * as fromLinks from './links';
import * as fromLayout from './layout';
export interface State{
layout: fromLayout.LayoutState
links: fromLinks.LinkState
}
const globalReducers = {
layoutReducer:fromLayout.layoutReducer,
linksReducer: fromLinks.linkReducer
};
const globalState: ActionReducer<State> = combineReducers(globalReducers);
export function reducers(state: any, action: any) { return globalState(state, action);}
/*layout*/
export const getLayoutState = (state: State) => state.layout;
export const getShowAddModal = createSelector(getLayoutState, fromLayout.getShowAddModal);
reducers/layout.ts
import { ActionReducer, Action } from '#ngrx/store';
import * as layoutActions from '../actions/layout';
export interface LayoutState {
showAddModal: boolean;
}
const initialState: LayoutState = {
showAddModal: false,
};
export function layoutReducer(state = initialState, action: Action): LayoutState {
switch (action.type) {
case layoutActions.TOGGLE_ADD_MODAL:
const newBoolState = state.showAddModal ? false : true ;
return {
showAddModal: newBoolState
};
default:
return state;
}
}
export const getShowAddModal = (state: LayoutState) => state.showAddModal; *** This is the undefined value
I am getting a TypeError: Cannot read property 'showAddModal' of undefined, in the method getShowAddModal in layout.ts. Any idea what I'm doing wrong? It is almost exact as in the example. Here is the reducer folder containing the files I have been closely following: https://github.com/ngrx/example-app/tree/master/src/app/reducers
Any help will be appreciated.

while retrieving passed array got from json in the second component,i am getting [object Object]

This is the first component where i am pushing those things into array named items and i am trying to get it in the second component through service
import { Component } from '#angular/core';
import { FormBuilder, FormControl } from '#angular/forms';
import {AppService} from '../second/app.service';
import { Router } from '#angular/router';
import { Http,Response } from '#angular/http';
import { routing, appRoutingProviders } from '../app.route';
import { Validators } from '#angular/forms';
import {BrowserModule} from '#angular/platform-browser';
#Component({
selector: 'first-app',
templateUrl:"../app/src/component/first/app.firstpage.html"
})
export class FirstComponent
{
data:any;
public items=[];
public edited=false;
public city=false;
public dateCon=false;
inputForm: FormGroup;
Select: FormControl;
Selectt: FormControl;
dat:FormControl;
constructor(private appservice:AppService,builder: FormBuilder, router:Router)
{
this.appservice.getData().subscribe(res=>{this.data=res.json()});
console.log(this.data);
this.Select = new FormControl('', [
Validators.required
]);
this.Selectt = new FormControl('', [
Validators.required
]);
this.dat = new FormControl('', [
Validators.required
]);
this.inputForm = builder.group({
Select: this.Select,
Selectt: this.Selectt,
dat: this.dat
});
this.router=router;
this.appservice=appservice;
}
ngOnInit(){
this.appservice.getData()
}
onclick(a,b) {
console.log(this.data);
let sel1=this.inputForm.value.Select;
let sel2=this.inputForm.value.Selectt;
let sel3=this.inputForm.value.dat;
console.log(sel3);
console.log(sel1);
console.log(sel2);
console.log(this.data.bus.length);
for(let i=0;i<this.data.bus.length;i++){
if((this.data.bus[i].from==sel1)&&(this.data.bus[i].to==sel2))
{
this.items.push(this.data.bus[i]);
}
}
this.appservice.setData(this.items);
}
if((sel1!="")&&(sel2!="")&&(sel3!="")&&(sel1!=sel2))
{
this.router.navigate(['/sec-component']);
}
else if((sel1=="")&&(sel2=="")&&(sel3==""))
{
this.edited=true;
}
if((sel1==sel2)&&((sel1!="")&&(sel2!="")))
{
this.edited=false;
this.city=true;
}
else
{
this.city=false;
}
if(sel1!=sel2)
{
this.edited=false;
}
if(sel3=="")
{
this.dateCon=true;
}
else
{
this.dateCon=false;
}
}
}
This is the second component to which i am passing this array and i need to get that printed over there and each properties to be accessed rather than the entire stuff.
import { Component } from '#angular/core';
import {AppService} from '../first/first.service';
#Component({
template:
`
<h1>second component</h1>
<h1>second component</h1>
<p >{{myName}}</p>
`
})
export class SecondComponent {
constructor(private appservice: AppService)
{
this.appservice=appservice;
this.myName=appservice.getVal();
}
}
This is the service page where i am returning the values
import {Component, Injectable,Input,Output,EventEmitter} from '#angular/core'
import { Http, Response } from '#angular/http';
export interface myData
{
name:any;
}
#Injectable()
export class AppService
{
sharingData: myData={name:""};
constructor(private http:Http){ }
getData()
{
return this.http.get('./app/src/component/busDet.json')
}
setData(i)
{
console.log('save data function called' + i + this.sharingData.name);
this.sharingData.name=i;
console.log(this.sharingData.name);
}
getVal()
{
console.log(this.sharingData.name);
return this.sharingData.name;
}
}
I am getting the output as object.object
I am not able to get the values with in the JSON in the next component.

Resources