Uncaught Error: Template parse errors in ionic when adding navigation - ionic-framework

I have this app I am building in Ionic and I tried adding navigation buttons from home page to both login and registration pages but when I add function (click)=”loginPage()” an error occured.
Below is the screenshot of the error:
App.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { RegisterPage } from '../pages/register/register';
#NgModule({
declarations: [
MyApp,
HomePage,
LoginPage,
RegisterPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
LoginPage,
RegisterPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { RegisterPage } from '../register/register';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
loginPage(){
this.navCtrl.push(LoginPage);
}
registerPage(){
this.navCtrl.push(RegisterPage);
}
}
And home.html
<ion-content padding class="home">
<ion-grid>
<ion-row>
<ion-col col-12 class="div-two">Welcome</ion-col>
</ion-row>
<ion-row justify-content-start>
<ion-col col-6 class="col">
<div><button ion-button round (click)=”loginPage()”>Login</button></div>
</ion-col>
<ion-col col-6 class="col">
<div><button ion-button round (click)=”registerPage()”>Register</button></div>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
I have tried all I could but still don't know what the cause of the error is. i am new to ionic.
Thanks.

Your double quote charater is invalid. Do not use ”loginPage()” but use "loginPage()".
This sometimes happens when you copy some code to editor directly. Please be careful about that.

Related

Ionic: How to use nav controller in app.component.ts

I am trying to develop an app in ionic 5. I added side menus in app.component.html along with ion-router-outlet. Now I want to navigate from side menus to my pages. I tried using router.navigate(['path']).
It navigates correctly, but the ion-back-button is not working on the navigated page.
These are my dependencies and version:
"dependencies": {
"#angular/common": "~10.0.0",
"#angular/core": "~10.0.0",
"#angular/forms": "~10.0.0",
"#angular/platform-browser": "~10.0.0",
"#angular/platform-browser-dynamic": "~10.0.0",
"#angular/router": "~10.0.0",
"#ionic-native/core": "^5.0.0",
"#ionic-native/splash-screen": "^5.0.0",
"#ionic-native/status-bar": "^5.0.0",
"#ionic/angular": "^5.0.0",
"cordova-android": "8.1.0",
"rxjs": "~6.5.5",
"tslib": "^2.0.0",
"zone.js": "~0.10.3"
}
my app.component.html
<ion-menu *ngIf="isSideDrawerAllowed()" side="start" menuId="first" contentId="main">
<ion-header>
<ion-toolbar translucent>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<!-- <ion-item (click)="navigateTo('/about-us')"> -->
<ion-item [routerLink]="['/about-us']">
<ion-icon name="mail" slot="start"></ion-icon>
<ion-label>About me</ion-label>
</ion-item>
<ion-item (click)="navigateTo('/schedule')">
<ion-icon name="paper-plane" slot="start"></ion-icon>
<ion-label>Schedule</ion-label>
</ion-item>
<ion-item (click)="navigateTo('/news')">
<ion-icon name="heart" slot="start"></ion-icon>
<ion-label>News</ion-label>
</ion-item>
<ion-item (click)="navigateTo('/gallary')">
<ion-icon name="archive" slot="start"></ion-icon>
<ion-label>Gallary</ion-label>
</ion-item>
</ion-list>
</ion-content>
</ion-menu>
<ion-router-outlet id="main"></ion-router-outlet>
app.component.ts
import { Component, OnInit, QueryList, ViewChildren } from '#angular/core';
import { Platform, AlertController, IonRouterOutlet, ToastController, NavController } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { Router, RouterModule } from "#angular/router";
import { Location } from '#angular/common';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
#ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private alertController: AlertController,
private toastController: ToastController,
private router: Router,
private location: Location
) {
this.initializeApp();
}
initializeApp() {
console.log('initializeApp')
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
isSideDrawerAllowed() {
let allowedRoutes = ["/", "/home"]
return allowedRoutes.includes(this.router.url)
}
navigateTo(url) {
this.router.navigateByUrl(url)
}
}
Please help me.
You don't need router or allowed routes. Your routes should already be set-up in app-routing.module.ts. Since you are not calling the ionic nav controller your URLs are not being added to the stack and so the back function does not work. navController knows about routes set-up in your routing modules.
Do this:
import { Component, OnInit } from '#angular/core';
import { Platform, NavController } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private navController: NavController
) {
this.initializeApp();
}
initializeApp() {
console.log('initializeApp')
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
navigateTo(url) {
this.navController.navigateForward(url);
}
}
NavController is deprecated as of Ionic 4, try using ion-nav (Nav).

Uncaught Error: Unexpected directive 'MatFormField' imported by the module 'AppModule'. Please add a #NgModule annotation

I Want to use Angular Material Date picker but I am getting this error.
Uncaught Error: Unexpected directive 'MatFormField' imported by the module 'AppModule'. Please add a #NgModule annotation.
app.component.html
<mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import {MatFormField} from '#angular/material';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MatFormField
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
To import components and directives etc, you import their modules, not the actual components and directives. So you need to import MatFormFieldModule instead of MatFormField:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { MatFormFieldModule } from '#angular/material/form-field';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MatFormFieldModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Ionic streaming media plugin issue

I'm trying to build an ionic app to stream audio feeds.
Here's what I have so far...
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { StreamingMedia } from '#ionic-native/streaming-media';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
StreamingMedia,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, private streamingMedia: StreamingMedia) {
}
playStream() {
let options: StreamingAudioOptions = {
bgColor: 'red',
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log('Error streaming') }
};
this.streamingMedia.playAudio('http://listen.radionomy.com:80/NewYorkClassicRock');
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>
If you get lost, the docs will be your guide.
</p>
<button ion-button large (click)="playStream()">Start the Stream!</button>
</ion-content>
Using ionic view, clicking the button does nothing in android or ios.
What am I doing wrong or missing?
Thanks!
It will not work in ionic view.
Run it on a physical device using the command:
cordova run android --debug
from within your app folder !
One small observation, you are setting the options but not passing it to the streamingMedia. You might want to do this:
this.streamingMedia.playAudio('http://listen.radionomy.com:80/NewYorkClassicRock',options);

Ionic 2 Yelp API

I'm trying to connect an Ionic 2 app to Yelp's API. Right now I'm just using a blank Ionic 2 application generated from the CLI and running on my localhost.
My code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '#angular/http';
import { Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
restaurants:any;
constructor(public navCtrl: NavController, public http: Http) {
var headers = new Headers();
headers.append('Authorization', 'Bearer someString');
var options = new RequestOptions({headers: headers});
this.http.get('https://api.yelp.com/v3/businesses/search?term=deli20&latitude=39.59754&longitude=-104.872934', options).map(res => res.json()).subscribe(data => {
this.restaurants = data.data.children;
console.log(this.restaurants);
});
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>
If you get lost, the docs will be your guide.
</p>
<!--Just using Ionic 2's default home page, just wanna output my JSON to the console for now.-->
</ion-content>
The page renders correctly, but the error I get in the console: "Failed to load resource: Preflight response is not successful"
The response looks like this:
{"error": {"code": "TOKEN_MISSING", "description": "An access token must be supplied in order to use this endpoint."}}
Any thoughts on what I might be missing?
Add this chrome plugin to your browser, turn it on and reload the page. It should work fine

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

I'm trying to implement Dynamic Forms in Angular 2. I've added additional functionalities like Delete and Cancel to the dynamic forms.
I've followed this documentation: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html
I've made some changes to the code. I'm getting error here.
How do i make this error go?
You can find the full code here: http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?p=preview , which is working in plunker but not in my local system.
Html code:
<div>
<form [formGroup]="form">
<div *ngFor="let question of questions" class="form-row">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input *ngSwitchCase="'textbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type" [(ngModel)]="question.value">
<select [id]="question.key" [(ngModel)]="question.value" *ngSwitchCase="'dropdown'" [formControlName]="question.key" >
<option *ngFor="let opt of question.options" [ngValue]="opt.key" >{{opt.value}}</option>
</select>
<input *ngSwitchCase="'checkbox'" [(ngModel)]="question.value"
[id]="question.key" [type]="question.type" (change)="question.value = ck.checked" #ck [ngModelOptions]="{standalone: true}">
</div>
<div class="errorMessage" *ngIf="!form.controls[question.key].valid">{{question.label}} is required</div>
</div>
<div class="form-row">
<button type="submit" [disabled]="!form.valid" (click)="onSubmit()">Save</button>
<button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>
<button type="button" class="btn btn-default" (click)="clear()">Clear</button>
</div>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>
Component code:
import { Component, Input, OnInit } from '#angular/core';
import { FormGroup, REACTIVE_FORM_DIRECTIVES } from '#angular/forms';
import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';
import { ControlGroup } from '#angular/common';
import {ChangeDetectorRef} from '#angular/core';
import { FormsModule } from '#angular/forms';
#Component({
selector: 'dynamic-form',
templateUrl: 'app/dynamicform/form.component.html',
directives: [REACTIVE_FORM_DIRECTIVES],
providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {
#Input() questions: QuestionBase<any>[] = [];
form: FormGroup;
payLoad:any;
payLoad2:any;
questiont: QuestionBase<any>;
questiond: QuestionBase<any>;
constructor(private qcs: QuestionControlService, private cdr: ChangeDetectorRef) { }
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
console.log("Form Init",this.questions);
this.questiont = JSON.parse(JSON.stringify(this.questions));
this.questiond = JSON.parse(JSON.stringify(this.questions));
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.payLoad2=this.payLoad;
this.questiont = JSON.parse(JSON.stringify(this.questions));
console.log("Submitted data",this.questions);
}
cancel(){
console.log("Canceled");
this.questions = JSON.parse(JSON.stringify(this.questiont));
}
clear(){
this.questions = JSON.parse(JSON.stringify(this.questiond));
this.questiont = JSON.parse(JSON.stringify(this.questiond));
console.log("Cleared");
this.cdr.detectChanges();
}
}
Figured out quick solution, update your #NgModule code like this :
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Source: Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’
In order to make ngModel work when using AppModules (NgModule ), you have to import FormsModule in your AppModule .
Like this:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [AppComponent]
})
export class AppModule {}
I encountered a similar error after upgrading to RC5; i.e. Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'.
The code on Plunker show you using Angular2 RC4, but the example code at https://angular.io/docs/ts/latest/cookbook/dynamic-form.html is using NGModule which is part of RC5. NGModules is a breaking change from RC4 to RC5.
This page explains the migration from RC4 to RC5: https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html
I hope this addresses the error you're getting and help get you going in the right direction.
In short, I had to create an NGModule in app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I then changed main.ts to use the module:
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
Of course, I also needed to update the dependencies in package.json. Here's my dependencies from package.json. Admittedly, I've hobbled them together from other sources (maybe the ng docs examples), so your mileage may vary:
...
"dependencies": {
"#angular/common": "2.0.0-rc.5",
"#angular/compiler": "2.0.0-rc.5",
"#angular/core": "2.0.0-rc.5",
"#angular/forms": "0.3.0",
"#angular/http": "2.0.0-rc.5",
"#angular/platform-browser": "2.0.0-rc.5",
"#angular/platform-browser-dynamic": "2.0.0-rc.5",
"#angular/router": "3.0.0-rc.1",
"#angular/router-deprecated": "2.0.0-rc.2",
"#angular/upgrade": "2.0.0-rc.5",
"systemjs": "0.19.27",
"core-js": "^2.4.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",
"angular2-in-memory-web-api": "0.0.15",
"bootstrap": "^3.3.6"
},
...
I hope this helps better. :-)
import {FormControl,FormGroup} from '#angular/forms';
import {FormsModule,ReactiveFormsModule} from '#angular/forms';
You should also add the missing ones.
You have just add FormsModule and import the FormsModule in your app.module.ts file.
import { FormsModule } from '#angular/forms';
imports: [
BrowserModule, FormsModule
],
Just add the above two lines in your app.module.ts. It's working fine.
You need to import FormsModule in your #NgModule Decorator, #NgModule is present in your moduleName.module.ts file.
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
Step to follow
1. Open your app.module.ts file.
.
2. Add import { FormsModule } from '#angular/forms';
.
3. Add FormsModule to imports asimports: [ BrowserModule, FormsModule ],
.
Final result will look like this
.....
import { FormsModule } from '#angular/forms';
.....
#NgModule({
.....
imports: [
BrowserModule, FormsModule
],
.....
})
To be able to use 'ngModule', the 'FormsModule' (from #angular/forms) needs to be added to your import[] array in the AppModule (should be there by default in a CLI project).
First import FormsModule from angular lib and under NgModule declared it in imports
import { FormsModule } from '#angular/forms';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
You need to import #angular/forms dependency to your module.
if you are using npm, install the dependency :
npm install #angular/forms --save
Import it to your module :
import {FormsModule} from '#angular/forms';
#NgModule({
imports: [.., FormsModule,..],
declarations: [......],
bootstrap: [......]
})
And if you are using SystemJs for loading modules
'#angular/forms': 'node_modules/#angular/forms/bundles/forms.umd.js',
Now you can use [(ngModel)] for two ways databinding.
For some reason in Angular 6 simply importing the FormsModule did not fix my issue. What finally fixed my issue was by adding
import { CommonModule } from '#angular/common';
#NgModule({
imports: [CommonModule],
})
export class MyClass{
}
Let’s assume, your old app.module.ts may look similar to this :
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Now import FormsModule in your app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
http://jsconfig.com/solution-cant-bind-ngmodel-since-isnt-known-property-input/
This answer may help you if you are using Karma:
I've did exactly as it's mentioned in #wmnitin's answer, but the error was always there. When use "ng serve" instead of "karma start", it works !
It's described on the Angular tutorial: https://angular.io/tutorial/toh-pt1#the-missing-formsmodule
You have to import FormsModule and add it to imports in your #NgModule declaraction.
import { FormsModule } from '#angular/forms';
#NgModule({
declarations: [
AppComponent,
DynamicConfigComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})