Angular 4 ReactiveForms Validation

666 views Asked by At

I'm trying to validate a custom element using model driven approach, ReactiveForms. I'm using tagsinput jquery library for that and creating additional fields for that form.

enter image description here

Component Code:

  declare var $:any;

    declare interface Variants {
        variants: Variant[]; 
    }

    declare interface Variant {
        optionName: string; 
        optionValues: string[];
    }

    ...
export class ProductsNewComponent implements OnInit, AfterViewInit {

    public myForm: FormGroup;
    constructor(private _fb: FormBuilder) {
    ...
    }

    ngOnInit() {

            this.myForm = this._fb.group({
                title: ['', [Validators.required, Validators.minLength(5)]],
                variants: this._fb.array([
                    this.initVariant(),
                ])
            });
    }

    initVariant() {
            return this._fb.group({
                optionName: ['', Validators.required],
                optionValues: ['', Validators.minLength(1)] <= tried
              //['', this.minLengthArray(1)]
                //this._fb.array([], this.minLengthArray(1))
                //['', Validators.compose([Validators.required, Validators.minLength(1)])]
                //Validators.minLength(1)]
                //this._fb.array([], Validators.minLength(1))

            });
        }

    ngAfterViewInit(){


        if($(".tagsinput").length != 0){

            $("#option_0").tagsinput({
                'onAddTag': this.tagsChange(0)
            });
        }

    }

Callback for tags components:

 tagsChange(id) {

            id = typeof id !== 'undefined' ? id : 0;
            //Gettings Values Array
            var array = $('#option_' + id).tagsinput();
            this.optionValues[id] = array[0].itemsArray;

            //Updating value
            const control = <FormArray>this.myForm.controls['variants'];

            control["controls"][id].patchValue({
                optionValues: this.optionValues[id]
            });

HTML Code:

<div formArrayName="variants" class="row">
    <div class="col-md-12" *ngFor="let variant of myForm.controls.variants.controls; let i=index ">
        <div [formGroupName]="i">
            <div class="col-md-6">
                <legend>Option Name {{i + 1}} 
                    <small class="category" *ngIf="myForm.controls.variants.controls.length > 1" (click)="removeOptions(i)">
                                                Remove
                    </small>
                </legend>
                <div class="form-group label-floating">
                    <input formControlName="optionName" type="text" class="form-control">
                </div>
                <small [hidden]="myForm.controls.variants.controls[i].controls.optionName.valid">
                       Option Name {{i+1}} is required
                </small>
            </div>
            <div class="col-md-6">
                <legend>Option Values</legend>

                <input id="option_{{i}}" formControlName="optionValues" value="" class="tagsinput" data-role="tagsinput" data-color="danger"
                /> {{optionValues[i] | json}}
                <!-- You can change data-color="rose" with one of our colors primary | warning | info | danger | success -->
                <small [hidden]="myForm.controls.variants.controls[i].controls.optionValues.valid">
                    Option Values {{i+1}} is required
                </small>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <button (click)="addOptions(i)" class="btn">
            Add Another Option
            <span class="btn-label btn-label-right">
                <i class="material-icons">keyboard_arrow_right</i>
            </span>
            <div class="ripple-container"></div>
        </button>
    </div>
</div>

Basically, when I add additional field to the form, everything is ok, but when I try to update that tags component, form still invalid. When I display in console, the form is valid, so currently I don't know how to validate that optionValues as array in a formGroup and also how to update the value if I change validation.

1

There are 1 answers

1
Imran Ahmad Ghazali On

Instead of using this you can use

<div class="panel panel-info">
                      <tag-input theme='minimal' name="tagName" [(ngModel)] = "tagName"></tag-input>
                    </div>

and in your component you can easily

tagName: this.tagName,

it will update the value in same way