Angular 2 ES6 - Sending event from component - ionic-framework

I want to send an custom event from Component in ES6, so I can listen to it in template <component (someEvent)="someFunction()">, but i cannot make it happen.
#Component's properties ouputs or events are breaking the application. Am I missing something?
this is my Component declaration:
import {Component, Output} from 'angular2/core';
#Component({
selector: 'section-navigator-component',
templateUrl: 'build/components/section_navigator/section_navigator.html',
inputs: [ 'resources', 'attr' ],
outputs: [ 'someEvent' ]
})
export class SectionNavigatorComponent {
constructor() {
}
resourceClickHandler($event, resource) {
}
}

This should work in your case:
import {Component, Output, EventEmitter} from 'angular2/core';
#Component({
selector: 'section-navigator-component',
templateUrl: 'build/components/section_navigator/section_navigator.html',
inputs: [ 'resources', 'attr' ],
outputs: [ 'someEvent' ]
})
export class SectionNavigatorComponent {
constructor() {
this.someEvent = new EventEmitter();
}
resourceClickHandler($event, resource) {
this.someEvent.emit(someValue);
}
}

You do not need to import 'Output' unless you use the alternate TypeScript syntax below:
import {Component, Input, Output, EventEmitter} from 'angular2/core';
#Component({
selector: 'section-navigator-component',
templateUrl: 'build/components/section_navigator/section_navigator.html'
})
export class SectionNavigatorComponent {
#Input() resources: any;
#Input() attr: any;
#Output() someEvent: EventEmitter<any> = new EventEmitter();
constructor() {
}
resourceClickHandler($event, resource) {
this.someEvent.emit(someValue);
}
}

Related

Issue with angular routing. pathMatch : 'full' not working when adding routers dynamically from DB

I have a setup as below.
I am adding router from my database into angular router module,
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { ApplicationDashboardComponent } from './components/application-dashboard/application-dashboard.component'
import { AppService } from './app.service'
import { HttpErrorResponse, HttpResponse } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router, protected appService: AppService) {
this.appService.getAllRoutes().subscribe(
(res: HttpResponse<string>) => {
let routerArray = <any>res.body;
if (routerArray !== undefined && routerArray !== 'null' && routerArray !== null) {
if (routerArray.length > 0) {
for (let i = 0; i < routerArray.length; i++) {
routerArray[i].component = ApplicationDashboardComponent;
this.router.config.push({ path: routerArray[i]['path'], component: ApplicationDashboardComponent, data: routerArray[i]['data'], pathMatch: 'full' });
}
}
console.log(this.router);
}
},
(res: HttpErrorResponse) => this.onError(res.message)
)
}
ngOnInit() {
}
protected onError(errorMessage: string) {
console.log(errorMessage);
}
}
And the app.routing.module.ts looks like below,
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AdminLogoutComponent } from './components/admin/admin-logout.component';
import { AdminComponent } from './components/admin/admin.component';
import { ApplicationDashboardComponent } from './components/application-dashboard/application-dashboard.component'
const routes: Routes = [
{path: '', component: ApplicationDashboardComponent, data:{portfolio:"Risk & Independence", fileName:"R&I-application-list.json"}, pathMatch : 'full'},
{path: 'admin', component: AdminComponent, pathMatch : 'full'},
{path: 'logout', component: AdminLogoutComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
For the ones already added in the route it works. But the ones I am adding from api add does not work without hash. If I try to go to the link without has it is giving me an error "Cannot match any routes. URL Segment"
I have tried to set usehash as false as well as pathlocationstrategy but nothing works.

Error: Can't resolve all parameters for Storage: (?, ?). ionic

I have had this error "NullInjectorError: No provider for Storage!" and then I add Storage in app.module.ts
then I had another error : Error: Can't resolve all parameters for Storage: (?, ?)
and sometime i had this error :
Uncaught TypeError: Cannot read property 'id' of undefined
core.js:24134 Uncaught TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (core.js:24134)
at core.js:24145
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:24145)
at new NgModuleFactory$1 (core.js:24242)
at compileNgModuleFactory__POST_R3__ (core.js:27786)
at PlatformRef.bootstrapModule (core.js:28024)
at Module../src/main.ts (main.ts:11)
at __webpack_require__ (bootstrap:84)
at Object.0 (main.ts:12
I tried importing IonicStorageModule and it is the same
app.moudle.page.ts file :
import { Component, OnInit } from '#angular/core';
import { NavController, NavParams, LoadingController, AlertController, ModalController } from '#ionic/angular';
import { PersonalinfoService } from 'src/app/services/personalinfo.service';
import { AlertService } from 'src/app/services/alert.service';
import { Saudi } from '../../../app/models/saudi';
import { ErrorsService } from '../../../app/services/errors.service';
#Component({
selector: 'app-personalinfo',
templateUrl: './personalinfo.page.html',
styleUrls: ['./personalinfo.page.scss'],
})
export class PersonalinfoPage{
public personal_info : any;
private loading : any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private personalinfoService : PersonalinfoService,
private errorsService : ErrorsService,
public modalCtrl: ModalController,
private loadingCtrl : LoadingController,
private alertCtrl : AlertController,
public storage: Storage,
) {
this.personal_info = this.navParams.get('personal_info') || new Saudi();
// هذذا حلو بس ماضبط
// this.loading = this.loadingCtrl.create({
// content: 'Please wait...',
// spinner: 'bubbles'
// });
}
ionViewDidLoad() {
console.log('ionViewDidLoad addInfoPage');
}
addInfo() {
let data = {
personal_info: this.personal_info
}
this.personalinfoService.store( JSON.stringify( data ) ).subscribe(
personal_info => {
this.personal_info = personal_info;
this.loading.dismiss();
this.dismiss( true );
},
);
}
closeModal(){
this.dismiss(false);
}
dismiss( returnParam : boolean ) {
let data = { 'personal_info': this.personal_info, 'returnParam': returnParam };
this.modalCtrl.dismiss( data );
}
}
Register.page.ts file
import { Component, OnInit } from '#angular/core';
import { ModalController, NavController } from '#ionic/angular';
import { LoginPage } from '../login/login.page';
import { AuthService } from 'src/app/services/auth.service';
import { NgForm } from '#angular/forms';
import { AlertService } from 'src/app/services/alert.service';
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
constructor(private modalController: ModalController,
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService
) { }
ngOnInit() {
}
dismissRegister() {
this.modalController.dismiss();
}
async loginModal() {
this.dismissRegister();
const loginModal = await this.modalController.create({
component: LoginPage,
});
return await loginModal.present();
}
register(form: NgForm) {
this.authService.register(form.value.name, form.value.email, form.value.password).subscribe(
data => {
this.authService.login(form.value.email, form.value.password).subscribe(
data => {
},
error => {
console.log(error);
},
() => {
this.dismissRegister();
this.navCtrl.navigateRoot('/personalinfo');
}
);
this.alertService.presentToast(data['message']);
},
error => {
console.log(error);
},
() => {
}
);
}
}
before i add personal page everythings works fine.
I have nothing else but there is an id added in the model
update :
I get steps back when it is working and starting again
the thing is it happand again
I have page called Home, Personalinfo
Home is called after success login and called personalinfo page in Home page
I have importing it like this: because I have got this error "No provider for PersonalinfoService!"
home-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePage } from './home.page';
import { PersonalinfoPage } from './../personalinfo/personalinfo.page';
const routes: Routes = [
{
path: '',
component: HomePage
}
];
#NgModule({
imports: [RouterModule.forChild(routes),
PersonalinfoPage
],
exports: [RouterModule],
})
export class HomePageRoutingModule {}
I DID MISS THE
#Injectable({
providedIn: 'root'
})
IN THE SERVICE FILE THATS WHERE CAME ALL THE MISS
THANK YOU
Like it's mentioned in the docs, you need to import IonicStorageModule.forRoot() in the AppModule:
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [
// ...
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot() // <--- here!
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: [
// ...
]
})
export class AppModule {}
Besides that, in your personalifo.ts file, you're injecting Storage but that's not actually Ionic's storage but the Web Storage API – you can see that when hovering on the Storage class:
In order to inject the right dependency, you'd need to add the following import at the top of the file: import { Storage } from '#ionic/storage'; to make sure you're using Ionic's storage:
import { Storage } from '#ionic/storage'; // <--- here!
// ...
#Component({
selector: 'app-personalinfo',
templateUrl: './personalinfo.page.html',
styleUrls: ['./personalinfo.page.scss'],
})
export class PersonalinfoPage {
constructor(
public storage: Storage,
// ...
) {}
}

Adding new components with default layout

I have just downloaded the angular admin template. Then i add a new component:
ng g n test
When I navigate to the component, the default layout is not applied. I guess it uses the app.component layout. How do you tell the component it should use the default UI?
to add a new componet follow these steps:
create a component-name-routing.module.ts file
create a component-name.module.ts file
create a component-name.component.html file
create a component-name.component.ts file
component-name.component.ts file:
import { Component, OnInit, Input } from "#angular/core";
#Component({
selector: 'app-componentName',
templateUrl: './component-name.component.html',
})
export class NameComponent implements OnInit {}
component-name-routing.module.ts file
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { NameComponent } from "./component-name.component";
const routes: Routes = [
{
path: '',
component: NameComponent,
data: {
title: 'route title'
},
children: [
{
path: '',
redirectTo: ''
},
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ComponentNameRoutingModule {}
component-name.module.ts file
// Angular
import { CommonModule } from '#angular/common';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
// Theme Routing
import { ComponentNameRoutingModule } from "./component-name-routing.module";
import { ComponentNameComponent } from "./component-name.component";
#NgModule({
imports: [
ComponentNameRoutingModule,
],
declarations: [
ComponentNameComponent
]
})
export class ComponentNameModule {
constructor() {}
}
all this in a new folder in the views directory and you'll be good to go.

Import class into ionic 3 and error when instantiating class

I'm new to ionic 3 and I'm trying to register. I have a accounts screen called accounts.ts that gets in src/pages/accounts/accounts.ts and then I'm trying to create a class where DAO will be referring to that class, I created it in the following src/dao/dao-accounts.ts location.
Some errors are showing up
My first doubt is this, do you mind this current?
import {DAOContas} from '../../dao/da-contacts';
I am also wanting to return a list of data but an error appears like this
:
uncaught (im promisse): referrererror: value is not defined
referenceerror: value is not defined at new ContasPage
class dao-accounts.ts
export class DAOContas {
constructor()
{
this.list = [];
}
getList()
{
this.list = [
{descricao:"Alimentação"},
{descricao:"Lazer"},
{descricao:"Transporte"}
];
return this.list;
}
}
method ContasPage.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DAOContas } from '../../dao/dao-contas';
#Component({
selector: 'page-list',
templateUrl: 'contas.html'
})
export class ContasPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.dao = new DAOContas();
this.listcontas = this.dao.getList();
}
}
Error Occurs When Instantiating DAOContas
So the issue here relates to dependency injection pattern. See official documentation of how that works for more info.
Based on the code you provided it seems like the issue is with the way you organized your code and declared (or did not declare) certain variables.
In your ContasPage do ensure you:
import the class
declare the vars
do assignments in the constructor
So in your case you didn't declare the vars before the constructor:
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DAOContas } from '../../dao/dao-contas';
#Component({
selector: 'page-list',
templateUrl: 'contas.html'
})
export class ContasPage {
// declare your vars here:
dao: any;
listcontas: any;
constructor(
public navCtrl: NavController
) {
this.dao = new DAOContas();
this.listcontas = this.dao.getList();
}
}
Same thing in your class you forgot to declare the var list:
export class DAOContas {
list: Array<{ descricao: string }>
constructor() {
this.list = [];
}
getList() {
this.list = [
{ descricao: "Alimentação" },
{ descricao: "Lazer" },
{ descricao: "Transporte" }
];
return this.list;
}
}
Also since your DAOContas to me looks like a data provider, I would probably think about turning it into a provider and injecting it into your page via constructor:
Make sure DAOContas is injectable:
import { Injectable } from '#angular/core'
#Injectable()
export class DAOContas {
list: Array<{ descricao: string }>
constructor() {
this.list = [];
}
getList() {
this.list = [
{ descricao: "Alimentação" },
{ descricao: "Lazer" },
{ descricao: "Transporte" }
];
return this.list;
}
}
Add it to your app.module.ts as provider:
import { DAOContas } from '../../src/providers/dao-contacts';
#NgModule({
declarations: [
bla
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
DAOContas,
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler },
TestProvider
]
})
export class AppModule { }
Finally inject it to your page:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { DAOContas } from '../../providers/dao-contacts';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage2 {
listcontas: any;
constructor(
public navCtrl: NavController,
public dao: DAOContas
) {
this.listcontas = this.dao.getList();
console.log(this.listcontas)
}
}

Self defined ionic2 component is not found

I have a login component with this code:
import { Injectable, Component } from '#angular/core';
import { Validators, FormBuilder } from '#angular/forms';
#Component({
selector: 'login',
templateUrl: 'login.html'
})
#Injectable()
export class LoginComponent {
login: any;
text: string;
constructor(private formBuilder: FormBuilder) {
this.text = 'Hello World';
}
ionViewLoaded() {
this.login = this.formBuilder.group({
title: ['', Validators.required],
description: [''],
});
}
doLogin(){
console.log(this.login.value)
}
}
I try to call it from the typescript file of page using
import { LoginComponent } from '../../component/login/login';
and
export class QuestionsPage {
constructor(public navCtrl: NavController, public loginComponent: LoginComponent ) {
}
Result is:
[13:23:46] typescript: src/pages/questions/questions.ts, line: 17
Cannot find name 'LoginComponent'.
which is the "constructor( public ..." line.
What do I do wrong?
Did you add your component to the #NgModules declarations array?
In your src/app/app.component.ts, add it like this:
import { LoginComponent } from '../../component/login/login';
#NgModule({
declarations: [
..
LoginComponent
..
]
})
You can read more here https://github.com/driftyco/ionic/blob/master/CHANGELOG.md#copying-your-project-to-a-new-project and here
https://angular.io/docs/ts/latest/guide/ngmodule.html