1
我在嘗試使用模型驅動方法ReactiveForms來驗證自定義元素。我正在使用tagsinput jquery庫,併爲該表單創建其他字段。Angular 4 ReactiveForms驗證
組件代碼:
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)
});
}
}
回調標籤組件:
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代碼:
<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>
基本上,當我添加另外al字段的形式,一切都很好,但是當我嘗試更新標籤組件時,表單仍然無效。當我在控制檯中顯示時,表單是有效的,所以目前我不知道如何驗證formValue作爲formGroup中的數組,以及如何更改驗證值。
當角一起使用jQuery你必須照顧自己的變化檢測。儘量避免這種情況。我建議使用這些標籤的角度版本。例如:https://github.com/Gbuomprisco/ngx-chips – ChrisY