Fix the TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement' - ionic-framework

I'm trying to setup Google Maps Places Autocomplete in an new Ionic app.
here is the problem. On the first search, I got this error in the console:
TypeError: Cannot read property 'place_id' of undefined
and this error in the terminal:
TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement'
However, on the second search I get the place_id without any error.
Here is my (simplified) .ts file
import { Component, OnInit } from '#angular/core';
import { google } from "google-maps";
import { Platform } from '#ionic/angular';
#Component({...})
export class AddaddressPage implements OnInit {
autocomplete:any;
constructor(public platform: Platform) {}
ngOnInit() {
this.platform.ready().then(() => {
this.autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
this.autocomplete.setFields(['place_id']);
});
}
fillInAddress() {
var place = this.autocomplete.getPlace();
console.log(place);
console.log(place.place_id);
}
}
and the input I use:
<input id="autocomplete" type="text" (change)="fillInAddress()" />
How should I proceed ?

After playing around, here is the trick! ViewChild and Ion-input are needed.
.html
<ion-input #autocomplete type="text"></ion-input>
.ts
import { Component, OnInit, ViewChild } from '#angular/core';
import { google } from "google-maps";
import { Platform } from '#ionic/angular';
#Component(...)
export class AddaddressPage implements OnInit {
googleAutocomplete:any;
#ViewChild('autocomplete') autocompleteInput: ElementRef;
constructor(public platform: Platform) { }
ngOnInit() {
this.platform.ready().then(() => {
this.autocompleteInput.getInputElement().then((el)=>{
this.googleAutocomplete = new google.maps.places.Autocomplete(el);
this.googleAutocomplete.setFields(['place_id']);
this.googleAutocomplete.addListener('place_changed', () => {
var place = this.googleAutocomplete.getPlace();
console.log(place);
console.log(place.place_id);
});
})
});
}
}

Related

Add Components dynamically in DOM ionic+angular

I am following How to Dynamically Create a Component in Angular to add components dynamically inside another component. I am receiving a weired error of undefined variable.
My Component file (MessComponent)
<template #messContainer>
<p>
mess works!
</p>
</template>
ts file
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-mess',
templateUrl: './mess.component.html',
styleUrls: ['./mess.component.scss'],
})
export class MessComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
Parent Component (hosting dynamic component)
module ts file
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { CommonModule } from '#angular/common';
import { IonicModule } from '#ionic/angular';
import { FormsModule } from '#angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';
import { MessComponent } from './../mess/mess.component';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
HomePageRoutingModule
],
declarations: [HomePage, MessComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
entryComponents: [MessComponent]
})
export class HomePageModule {}
ts file
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, ComponentFactory, OnInit } from "#angular/core";
import { MessComponent } from "./../mess/mess.component";
#Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"],
})
export class HomePage implements OnInit {
componentRef: any;
#ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;
createComponent() {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(MessComponent);
this.componentRef = this.entry.createComponent(factory);
}
destroyComponent() {
this.componentRef.destroy();
}
constructor(private resolver: ComponentFactoryResolver) {}
ngOnInit(): void {
this.createComponent();
}
}
and the error I am receiving
Uncaught (in promise): TypeError: this.entry is undefined
I understand this is claiming regarding the variable entry, but don't understand why it is not identifying that variable. To conclude, why I cannot add the component?
Solved it. Actually I was passing wrong param to the #ViewChild(''). I was passing the template name (container) of the child while I should have passed the container name in the parent component. So created a div in the parent component with #messContainer and corrected the #ViewChild
Important!:
now #messContainer is in the parent component and everything works as expected.
#ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;

Problem when I want to work on a different version in Ionic dashboard

I have a version deployed in the Ionic dashboard, and every time that I'm working on a new version and the device is connected to the Internet, it's replacing my version with the version that is deployed there. How can I work on a new version?
You can check if your device is connected to internet or not, using this network plugin provided by ionicframework.
let disconnectSubscription = this.network.onDisconnect().subscribe(() => { console.log('network was disconnected :-(');});
This metod will automatically catch if user disconnected their network and
let connectSubscription = this.network.onConnect().subscribe(() => {console.log('network connected!');});
using this method you can catch if user is connected to network.
So using those method you can show/hide some content for offline and online use.
I have created network service to catch Online and Offline status :
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network/ngx'
import { BehaviorSubject, Observable } from 'rxjs';
import { ToastController, Platform } from '#ionic/angular';
export enum ConnectionStatus {
Online,
Offline
}
#Injectable({
providedIn: 'root'
})
export class NetworkService {
private status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(ConnectionStatus.Offline);
constructor(private network: Network, private toastController: ToastController, private plt: Platform) {
this.plt.ready().then(() => {
this.initializeNetworkEvents();
let status = this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline;
this.status.next(status);
});
}
public initializeNetworkEvents() {
this.network.onDisconnect().subscribe(() => {
if (this.status.getValue() === ConnectionStatus.Online) {
this.updateNetworkStatus(ConnectionStatus.Offline);
}
});
this.network.onConnect().subscribe(() => {
if (this.status.getValue() === ConnectionStatus.Offline) {
this.updateNetworkStatus(ConnectionStatus.Online);
}
});
}
private async updateNetworkStatus(status: ConnectionStatus) {
this.status.next(status);
let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online';
let toast = this.toastController.create({
message: `You are now ${connection}`,
duration: 3000,
position: 'bottom'
});
toast.then(toast => toast.present());
}
public onNetworkChange(): Observable<ConnectionStatus> {
return this.status.asObservable();
}
public getCurrentNetworkStatus(): ConnectionStatus {
return this.status.getValue();
}
}
And you can you this service in your component, for example:
import { Component, OnInit } from '#angular/core';
import { NetworkService, ConnectionStatus } from 'src/services/network.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.page.html',
styleUrls: ['./dashboard.page.scss'],
})
export class DashboardPage implements OnInit {
isOnline:boolean;
constructor(private network: NetworkService){}
ngOnInit() {
let status = this.network.getCurrentNetworkStatus();
(status == ConnectionStatus.Offline)? this.isOnline = false: this.isOnline = true;
console.log("Network status is ", this.isOnline);
}
}
<ion-header>
</ion-header>
<ion-content>
<ion-row *ngIf="isOnline">
For online
</ion-row>
<ion-row *ngIf="!isOnline">
For Offline
</ion-row>
</ion-content>

ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I'm working on autocomplete-search with angular 4. This search bar will get books information from Google Books API. It works fine when I input any search terms. But it causes an error if I remove the entire search term or input a space.This is the error I got
This is my SearchComponent.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-admin-search',
templateUrl: './admin-search.component.html',
styleUrls: ['./admin-search.component.css']
})
export class AdminSearchComponent implements OnInit {
books: any[] = [];
searchTerm$ = new Subject<string>();
constructor (private bookService: BookService,
private http: HttpClient
) {
this.bookService.search(this.searchTerm$)
.subscribe(results => {
this.books = results.items;
});
}
ngOnInit() {
}
This is my SearchComponent.html
<div>
<h4>Book Search</h4>
<input #searchBox id="search-box"
type="text"
placeholder="Search new book"
(keyup)="searchTerm$.next($event.target.value)"/>
<ul *ngIf="books" class="search-result">
<li *ngFor="let book of books">
{{ book.volumeInfo.title }}
</li>
</ul>
</div>
This is my BookService.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Book } from './book';
import { BOOKS } from './mock-books';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
#Injectable()
export class BookService {
private GoogleBookURL: string = "https://www.googleapis.com/books/v1/volumes?q=";
constructor (private http: HttpClient) { }
search(terms: Observable<string>) {
return terms.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => this.searchEntries(term));
}
searchEntries(searchTerm: string) {
if (searchTerm.trim()) {
searchTerm = searchTerm.replace(/\s+/g, '+');
let URL = this.GoogleBookURL + searchTerm;
return this.http.get(URL);
}
}
}
Can someone help me out? Thanks in advance!
Your method searchEntries returns value (Observable<Response>) only if searchTerm.trim() is true (so it must return non-empty string).
There can be situation that searchEntries will return undefined instead of Obervable<Response> if trim() returns '' (empty string which is false). You can't pass undefined returned from searchEntries into .switchMap(term => this.searchEntries(term));.
For that case your code will look like this:
.switchMap(term => undefined) which is not valid construction.

passing parameter between pages ionic

Hi i´m new in ionic and I am trying to pass the scann information form one page to another, the thing its that when I execute the program I have a console.log to check if the info its passed correctly but on chrome console said undefined, letme paste my code:
home.ts where i try to send the info from the scan:
import { Component } from '#angular/core';
import { NavController,Platform } from 'ionic-angular';
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
import { TabsPage } from '../tabs/tabs';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private barcodeText:String;
private barcodeFormat:String;
private platform:Platform;
private navController:NavController;
constructor(private barcodeScanner: BarcodeScanner,public navCtrl: NavController,platform:Platform) {
this.platform = platform;
this.navController = navCtrl;
}
doScan(){
console.log('scannig product barcode');
this.platform.ready().then(() => {
this.barcodeScanner.scan().then((result) => {
if (!result.cancelled) {
this.barcodeText = result.text;
this.scanningDone(this.barcodeText)
}
}, (error) => {
console.log('error when scanning product barcode');
});
});
}
scanningDone(data){
this.navController.push(TabsPage,{
data:data
});
}
main.ts where the info suppose to go:
import { Component } from '#angular/core';
import { NavController, NavParams , ToastController} from 'ionic-angular';
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
import { DetailsPage } from '../details/details';
import { Http } from '#angular/http'
#Component({
selector: 'main',
templateUrl: 'main.html'
})
export class MainPage {
information: any[];
item:any;
private bcData;
constructor(public navCtrl: NavController, private http: Http,public params:NavParams) {
this.bcData = params.get('data');
console.log(params.get('data'));
let localData = http.get(this.bcData).map(res => res.json().items);
localData.subscribe(data => {
this.information = data;
})
}
on the console.log(params.get('data')); its where I get the undefinied on the console.
you could have a method in your TabsPage that handles opening and closing pages like this:
openPages(Page, Data){
this.navCtrl.push(Page,Data);
}
Then in your scanningDone Method:
scanningDone(data){
this.tabsPage.openPages(MainPage,{
data:data
});
}
How about using localStorage
look at this as well

Assigning an import to a variable within a constructor

I am building an app in Ionic2. I want to implement Facebook within the app and so I am trying to use the ionic-native Facebook api. I imported it and then attempted to assign it to a variable so I could use the functions associated with it.
Here is my code.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
#Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {
fb: any;
constructor(public navCtrl: NavController, facebook: Facebook) {
this.fb = facebook;
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
this.fb.login([]);
ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}
}
I thought an import works much like a class in that you can import it and assign it to a variable and then have access to its methods. Does it not work like that? How does it work?
You just have to import Facebook class like it is said in Ionic native docs :
https://ionicframework.com/docs/v2/native/
You don't need to inject it through the constructor. As method are static this will print an error.
Be sure to also call Facebook after platform.ready event. And don't forget to add the plugin. See your example modified accordingly.
import { Component } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Facebook } from 'ionic-native';
#Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {
constructor(public navCtrl: NavController, platform: Platform) {
platform.ready().then(() => {
console.log('Faceboook');
Facebook.login([]).then((response) => {
console.log(response);
}).catch((error) => {
console.error(error);
});
})
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}
}