nik
nik

Reputation: 2483

Angular 2 : Adding a required validation to textbox without ngmodel binding

Requirement : Format a list to a text box as comma separated values. For example, my component is as follows

    import { Component } from '@angular/core';

    @Component({
        template: `
        <input 
            style="width:400px;"
            (focusout)="update($event.target.value);" 
            value="{{hobbies.join(', ')}}"
            #ipHobbies
        />
        <br>
        {{hobbies}}
        `
    })

    export class TestComponent {
        hobbies: string[] = ["painting", "cooking", "swiming"];
        update(csvHobbies): void {
            csvHobbies = csvHobbies.trim();
            this.hobbies = csvHobbies.split(",")
                .map((item) => { return item.trim() })
                .filter((item) => { return item != "" });
        }
    }

Output :

Output

Question

Is there a better way to implement this ? How do I add required validation message to user ?

Upvotes: 0

Views: 1029

Answers (1)

nik
nik

Reputation: 2483

I could add required validation message by adding isEmpty property to local variable #ipHobbies and updating it on focusout event.

    import { Component } from '@angular/core';
    @Component({
        template: `
        <input 
            (focusout)="ipHobbies.isEmpty=!update($event.target.value);" 
            value="{{hobbies.join(', ')}}"
            #ipHobbies
        />
        <div *ngIf="ipHobbies.isEmpty">
            <span 
                [hidden]="!ipHobbies.empty" 
                class="label label-warning"
            >
            Hobbies are required
            </span>
        </div>    
        `
    })

    export class TestComponent {
        hobbies: string[] = ["painting", "cooking", "swiming"];
        update(csvHobbies): boolean {
            if (csvHobbies == "") {
                this.hobbies = [];
                return false;
            }
            csvHobbies = csvHobbies.trim();
            this.hobbies = csvHobbies.split(",")
                .map((item) => { return item.trim() })
                .filter((item) => { return item != "" });
            return true;
        }
    }

Output

enter image description here

Please update if there is a better way to implement this.

Upvotes: 1

Related Questions