0

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.