How to create a custom form component by extending BaseInput in ionic2 - ionic-framework

I want to create a custom form input component in ionic2, by extending BaseInput. But it doesn't rendered, and I can't find it on the DOM.
import { Component, ElementRef, OnDestroy, Optional, Renderer,
ViewEncapsulation } from "#angular/core";
import { Config, Form, Item } from "ionic-angular";
import { BaseInput } from "ionic-angular/util/base-input";
import { NG_VALUE_ACCESSOR } from "#angular/forms";
#Component({
selector: 'my-checkbox',
template:
'<p>aaaaa</p>',
host: {
'[class.checkbox-disabled]': '_disabled'
},
providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: MyCheckboxComponent, multi: true } ],
encapsulation: ViewEncapsulation.None,
})
export class MyCheckboxComponent extends BaseInput<any> implements OnDestroy {
constructor(form: Form, config: Config, elementRef: ElementRef, renderer: Renderer, #Optional() item: Item) {
super(config, elementRef, renderer, 'my-checkbox', [], form, item, null);
}
}
The code is copy from src/component/checkbox/checkbox.ts and make a little changes.

I had the same problem. My component did not get render within <ion-item> parent element. I fixed it by adding item-content directive
<ion-item>
<ion-label>Label</ion-label>
<my-checkbox item-content></my-checkbox>
</ion-item>

Related

Ionic 4 pass property to custom component

I've written a custom component to handle my ion-header as all I need to change per page is the title. However, the title is not displaying as the component doesn't seem to be getting the property from the app page.
Component Template
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title> {{title}} </ion-title>
Component Typescript
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-custom-toolbar',
templateUrl: './custom-toolbar.component.html',
styleUrls: ['./custom-toolbar.component.scss'],
})
export class CustomToolbarComponent implements OnInit {
#Input() title: any;
constructor() { }
ngOnInit() {
}
}
App Page Template
<app-custom-toolbar [title]="Dashboard"></app-custom-toolbar>
You need to declare #Input() title in your custom component to pass value from parent into it like -
Child Component
...
...
#Input() title: any;
...
...
Parent Component HTML -
<child-component [title]="somePropertyInParentComponent"></child-component>
Edit: According to your updated question . Try removing [] from the title property in parent component
As Pawan Sharma says, you need to declare an #Input,
In this link you can find more information about it.
https://victorroblesweb.es/2016/11/07/input-output-angular-2/
Typescript
import { Component, OnInit, Input } from '#angular/core';
import { NavController } from '#ionic/angular';
#Component({
selector: 'app-footertoolbar',
templateUrl: './footertoolbar.page.html',
})
export class FooterToolbarPage implements OnInit {
#Input() public activeIndex:number;
constructor(private navCtrl: NavController) { }
ngOnInit() {}
public GoToPage() { console.log(this.activeIndex); }
}
HTML
<ion-toolbar color="dark">
<ion-buttons class="sidemargin" slot="secondary">
<ion-button (click)="GoToPage()"></ion-button>
</ion-buttons>
</ion-toolbar>
HTML of the component that use the component
<app-footertoolbar [activeIndex]="0" >
</app-footertoolbar>
Reposting my comment as requested:
I think if you have the [] around it then to pass a string back you would need "'dashboard'" (so a " with a ' inside it).

RadListView doesn't display items

I am having much difficulties implementing RadListView in my application. According to documentation the ListView accepts items as an ObservableArray, but regardless of whether that or plain array is used, items are not being displayed. I prepared a sample app in the Playground
https://play.nativescript.org/?template=play-ng&id=39xE2X&v=11
Component is like this:
import { Component, ViewChild, OnInit, ChangeDetectorRef, ElementRef } from "#angular/core";
import { GestureTypes, PanGestureEventData, TouchGestureEventData } from "tns-core-modules/ui/gestures";
import { ObservableArray } from "tns-core-modules/data/observable-array";
#Component({
selector: "ns-app",
moduleId: module.id,
templateUrl: "./app.component.html",
})
export class AppComponent implements OnInit {
public gridData = []; //new ObservableArray<any>();
constructor(
private cd: ChangeDetectorRef
) {
this.feedTestData();
}
ngOnInit() {
}
ngAfterViewInit() {
}
public detectChanges() {
this.cd.detectChanges();
}
private feedTestData() {
let data = [
{
description: 'line 1',
},
{
description: 'line 2',
},
];
this.gridData.splice(0, 0, data);
}
}
and template like this:
<GridLayout tkExampleTitle tkToggleNavButton>
<RadListView [items]="gridData">
<ng-template tkListItemTemplate let-item="item">
<StackLayout orientation="vertical">
<Label [text]="description"></Label>
</StackLayout>
</ng-template>
</RadListView>
</GridLayout>
What's perplexing me even more is that in my real application RadListView displays something, but does it on its own, completely ignoring my template. I can literally leave nothing inside RadListView, but it would still display items
I have updated your playground and it is working now.
https://play.nativescript.org/?template=play-ng&id=39xE2X&v=12
You were trying to access the description in ng-template while it should be item.description
<Label [text]="item.description"></Label>
Also for the testing purpose, I am creating an Onservable array from your data. this.gridData = new ObservableArray(data); in your feedTestData function.

Multiple component in shared.module.ts Ionic

i am new to ionic and recently i tried to create a shared component so that i can sort of remove duplicate coding of same content on different page. It consist of a notification bar and a panel that have a login/signup button. I am able to display the notification bar and the login panel on pages that i want but i am unable to call the function of the login/signup button.
Whenever i click the login/signup button, it will said presentLoginModal() is not a function. Below are my code.
Hope someone can advice me on this. Thanks.
shared.module.ts
import {NgModule} from '#angular/core';
import {IonicPageModule} from 'ionic-angular';
import {NotificationComponent} from '../notification/notification';
import {NonLoginComponent} from '../nonlogin/nonlogin';
#NgModule({
imports: [IonicPageModule.forChild(NotificationComponent),IonicPageModule.forChild(NonLoginComponent)],
declarations: [NotificationComponent, NonLoginComponent],
exports: [NotificationComponent, NonLoginComponent]
}) export class SharedModule {}
nonlogin.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Login} from '../login/login';
import {Register} from '../register/register'
#IonicPage()
#Component({
selector: 'app-nonlogin',
templateUrl: './nonlogin.html'
})
export class NonLoginComponent {
constructor(public navCtrl: NavController) {}
presentLoginModal() {
let loginModal = this.modalCtrl.create(Login, {showBackdrop: true, enableBackdropDismiss: true},{cssClass: 'logon'});
loginModal.present();
}
presentRegisterModal(){
let registerModal = this.modalCtrl.create(Register, {showBackdrop: true, enableBackdropDismiss: true},{cssClass: 'register'});
registerModal.present();
}
}
notification.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
#Component({
selector: 'app-notification',
templateUrl: './notification.html'
})
export class NotificationComponent {
constructor(public navCtrl: NavController) {}
}
nonlogin.html
<div class="toppanel"><div class="leftside"><img class="companylogo"
src="../../assets/imgs/logo.jpg"></div><div class="rightside">
<button tappable class="login" ion-button
(click)="presentLoginModal()">LOG IN</button><button tappable
class="signup" ion-button (click)="presentRegisterModal()">SIGN
UP</button></div></div>
home.html
<ion-content>
<app-notification></app-notification>
<app-nonlogin></app-nonlogin>
</ion-content>

Inheriting validation using ControlValueAccessor in Angular

I have a custom form control component (it is a glorified input). The reason for it being a custom component is for ease of UI changes - i.e. if we change the way we style our input controls fundamentally it will be easy to propagate change across the whole application.
Currently we are using Material Design in Angular https://material.angular.io
which styles controls very nicely when they are invalid.
We have implemented ControlValueAccessor in order to allow us to pass a formControlName to our custom component, which works perfectly; the form is valid/invalid when the custom control is valid/invalid and the application functions as expected.
However, the issue is that we need to style the UI inside the custom component based on whether it is invalid or not, which we don't seem to be able to do - the input that actually needs to be styled is never validated, it simply passes data to and from the parent component.
COMPONENT.ts
import { Component, forwardRef, Input, OnInit } from '#angular/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
} from '#angular/forms';
#Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputComponent),
multi: true
}
]
})
export class InputComponent implements OnInit, ControlValueAccessor {
writeValue(obj: any): void {
this._value = obj;
}
registerOnChange(fn: any): void {
this.onChanged = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
get value() {
return this._value;
}
set value(value: any) {
if (this._value !== value) {
this._value = value;
this.onChanged(value);
}
}
#Input() type: string;
onBlur() {
this.onTouched();
}
private onTouched = () => {};
private onChanged = (_: any) => {};
disabled: boolean;
private _value: any;
constructor() { }
ngOnInit() {
}
}
COMPONENT.html
<ng-container [ngSwitch]="type">
<md-input-container class="full-width" *ngSwitchCase="'text'">
<span mdPrefix><md-icon>lock_outline</md-icon> </span>
<input mdInput placeholder="Password" type="text" [(ngModel)]="value" (blur)="onBlur()" />
</md-input-container>
</ng-container>
example use on page:
HTML:
<app-input type="text" formControlName="foo"></app-input>
TS:
this.form = this.fb.group({
foo: [null, Validators.required]
});
You can get access of the NgControl through DI. NgControl has all the information about validation status. To retrieve NgControl you should not provide your component through NG_VALUE_ACCESSOR instead you should set the accessor in the constructor.
#Component({
selector: 'custom-form-comp',
templateUrl: '..',
styleUrls: ...
})
export class CustomComponent implements ControlValueAccessor {
constructor(#Self() #Optional() private control: NgControl) {
this.control.valueAccessor = this;
}
// ControlValueAccessor methods and others
public get invalid(): boolean {
return this.control ? this.control.invalid : false;
}
public get showError(): boolean {
if (!this.control) {
return false;
}
const { dirty, touched } = this.control;
return this.invalid ? (dirty || touched) : false;
}
}
Please go through this article to know the complete information.
Answer found here:
Get access to FormControl from the custom form component in Angular
Not sure this is the best way to do it, and I'd love someone to find a prettier way, but binding the child input to the form control obtained in this manner solved our issues
In addition: Might be considered dirty, but it does the trick for me:
let your component implement the Validator interface.
2 In the validate function you use the controlcontainer to get to the outer formcontrol of your component.
Track the status of the parent form control (VALID/INVALID) by using a variable.
check for touched. and perform validation actions on your fields only when touched is true and the status has changed.

Fire Nativescript tabitem event when tabitem gets selected

I am using a Nativescript (Angular 2) TabView with two TabItems. The XML is divided intro three files. One that holds the TabView and two others for each TabItem. Therefore I also have three TypeScript components.
At the moment I am loading data in the second TabItem's onInit method. The problem is that this action already happens when the first TabItem of the TabView is being displayed/loaded.
What is the best practice to load this data only when the second TabItem is selected?
This is my (shortened) code:
home.page.html:
<ActionBar title="Home"></ActionBar>
<TabView #tabview (selectedIndexChanged)="tabIndexChanged($event)" toggleNavButton>
<StackLayout *tabItem="{title: 'Tab 1'}">
<tab1></tab1>
</StackLayout>
<StackLayout *tabItem="{title: 'Tab 2'}">
<tab2></tab2>
</StackLayout>
</TabView>
home.page.ts:
import {Component} from "#angular/core";
#Component({
selector: "home-page",
templateUrl: "./pages/home/home.page.html",
providers: []
})
export class HomePage {
public activeTab: string;
public constructor() {
}
public tabIndexChanged(e: any) {
switch (e.newIndex) {
case 0:
console.log(`Selected tab index: ${e.newIndex}`);
break;
case 1:
console.log(`Selected tab index: ${e.newIndex}`);
break;
default:
break;
}
}
}
tab1.tab.html:
<StackLayout orientation="vertical" class="p-20">
<Label text="Tab 1"></Label>
</StackLayout>
tab1.tab.ts:
import { Component, OnInit } from "#angular/core";
#Component({
selector: "tab1",
templateUrl: "./pages/partials/tab1.tab.html",
providers: []
})
export class Tab1 implements OnInit {
public constructor() {}
public ngOnInit() {
console.log("init Tab 1");
}
}
tab2.tab.html:
<StackLayout orientation="vertical" class="p-20">
<Label text="Tab 2"></Label>
</StackLayout>
tab2.tab.ts:
import { Component, OnInit } from "#angular/core";
#Component({
selector: "tab2",
templateUrl: "./pages/partials/tab2.tab.html",
providers: []
})
export class Tab2 implements OnInit {
public constructor() {}
public ngOnInit() {
console.log("init Tab 2");
this.getSomeDataViaHttp();
}
private getSomeDataViaHttp() {
//getting data from an API
}
}
Is there an Angular 2 / Nativescript event other than onInit that would help here?
Or should I use the method tabIndexChanged in the home.page.ts for that?
Or put all the logic and the XML for the TabView back into one xml file and one ts file?
What is best practice?
You could use a service and a Subject as followed.
Import the service file in all ts files (use the name and location you like):
import { NavService } from "./services/nav.service";
Make sure to import it also in your app.module.ts to generally load it:
import { NavService } from "./services/nav.service";
#NgModule({
declarations: [
AppComponent,
],
bootstrap: [AppComponent],
imports: [
],
providers: [
NavService
]
})
export class AppModule {}
Create the service file in the specified location with the following content:
import { Injectable } from "#angular/core";
import { Subject } from "rxjs";
#Injectable()
export class NavService {
private currentState = new Subject<any>();
constructor () {
}
setCurrentState(navPoint: number){
this.currentState.next(navPoint);
}
getCurrentState() {
return this.currentState.asObservable();
}
}
Change the tab2.tab.ts to the following:
import { Component, OnInit } from "#angular/core";
import { NavService } from "./services/nav.service";
#Component({
selector: "tab2",
templateUrl: "./pages/partials/tab2.tab.html",
providers: []
})
export class Tab2 implements OnInit {
public constructor(private _navService: NavService) {}
public ngOnInit() {
console.log("init Tab 2");
this._navService.getCurrentState().subscribe(
(state) => {
if (state == {{something}}) {
//write your code here which should be executed when state has the property {{something}}
this.getSomeDataViaHttp();
}
}
);
}
private getSomeDataViaHttp() {
//getting data from an API
}
}
Call the setCurrentState of the service in your home.page.ts:
import {Component} from "#angular/core";
import { NavService } from "./services/nav.service";
#Component({
selector: "home-page",
templateUrl: "./pages/home/home.page.html",
providers: []
})
export class HomePage {
public activeTab: string;
public constructor(private _navService: NavService) {
}
public tabIndexChanged(e: any) {
this._navService.setCurrentState(e.newIndex);
}
}
Take care that the "typeof" setting and getting the state is correct.