Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 71529

Wrap ion-input for a custom Reactive Form component

$
0
0

@ffalcinelli wrote:

Hi all,

I’m using ionic 4 and I’d like to build a reusable form component. Probably it’s easy but my lack of knowledge is not helping me find the best way to achieve it.

Say I have a password input, with a toggle icon to show/hide the password. This could appear in at least 3 places: login, register and reset pages.

So one of these forms could be something like:

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
    <ion-item>
        <ion-label position="floating">Email</ion-label>
        <ion-input name="email" type="email" formControlName="email"></ion-input>
    </ion-item>
    <app-password-item [form]="loginForm" formControlName="password"></app-password-item>
    <ion-button type="submit" [disabled]="loginForm.invalid" expand="block">Sign in!
    </ion-button>
</form>

...
    ngOnInit() {
        this.loginForm = this.formBuilder.group({
            email: ['', [Validators.required, Validators.email]],
            password: ['', [Validators.required]]
        });
    }
...

And my <app-password-item> would be

<ion-item>
    <ion-label position="floating">Password</ion-label>
    <ion-input name="password" [type]="passwordType" clearOnEdit="false"></ion-input>
    <ion-icon [name]="passwordIcon" class="password-icon" (click)='hideShowPassword()' slot="end"></ion-icon>
</ion-item>

And the corresponding typescript file:

import {Component, Input, OnInit} from '@angular/core';
import {FormGroup} from '@angular/forms';

@Component({
    selector: 'app-password-item',
    templateUrl: './password-item.component.html',
    styleUrls: ['./password-item.component.scss']
})
export class PasswordItemComponent implements OnInit {
    @Input() form: FormGroup;
    passwordType = 'password';
    passwordIcon = 'eye-off';

    constructor() {}

    ngOnInit() {}

    hideShowPassword() {
        this.passwordType = this.passwordType === 'text' ? 'password' : 'text';
        this.passwordIcon = this.passwordIcon === 'eye' ? 'eye-off' : 'eye';
    }
}

I’ve not put any css and other cosmetics to be short.

Now, I read about ControlValueAccessor, but I don’t understand if it’s the right choice, since I don’t want to create a custom control, but just wrap an existing one so that I can reuse it without copy/paste abuse.

I’m sorry if this has been asked before, but I didn’t find any similar post… Any suggestion is much appreciated!

Thank you all, ciao,
Fabio

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 71529

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>