我尝试使用模型驱动方法ReactiveForms验证自定义元素。我正在使用 tagsinput jquery库并为该表单创建其他字段。
组件代码:
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>
基本上,当我向表单添加其他字段时,一切正常,但是当我尝试更新该标记组件时,表单仍然无效。当我在控制台中显示时,表单是有效的,所以目前我不知道如何在formGroup中验证optionValues作为数组,以及如果我更改验证如何更新值。
答案 0 :(得分:0)
您可以使用
而不是使用它<div class="panel panel-info">
<tag-input theme='minimal' name="tagName" [(ngModel)] = "tagName"></tag-input>
</div>
在您的组件中,您可以轻松
tagName: this.tagName,
它将以相同的方式更新值