从this response添加提供:NG_VALIDATORS,删除所需并添加验证功能,如
public setDisabledState?(isDisabled: boolean): void { }
validate(control:any){
return this.model?null:{required:true}
}
your forked stackblitz
更新
当我们使用带有 [(ngModel)] 的字符串数组(或数字数组)时会出现问题。
这行不通
{{model.loopValues|json}}
//NOT WORK
<div *ngFor="let n of model.loopValues; let i = index;">
<input [(ngModel)]="n"
name="{{'ct'+i}}" #control="ngModel"></custom-text>
</div>
因为 ngModel 绑定在临时变量“n”上,所以不起作用。如果 model.loopValues 是一个对象数组,那么这项工作是因为绑定了对象的“内存位置”。
我们可以考虑一下
//NOT WORK
<div *ngFor="let n of model.loopValues; let i = index;">
<input [(ngModel)]="model.loopValues[i]"
name="{{'ct'+i}}" #control="ngModel"></custom-text>
</div>
并且不起作用,因为当我们更改输入时,由于 Angular 再次渲染 *ngFor 而失去焦点
我的想法在.ts中有一个与model.loopValues长度相同的数组
array=new Array(this.model.loopValues.length)
现在我们可以做
<div *ngFor="let n of array; let i = index;">
<custom-text [(ngModel)]="model.loopValues[i]"
name="{{'ct'+i}}" #control="ngModel"></custom-text>
</div>
奖励:我们可以使用repeat directive 并写一些喜欢
<div *repeat="model.loopValues.length;let i">
<custom-text [(ngModel)]="model.loopValues[i]"
name="{{'ct'+i}}" #control="ngModel"></custom-text>
</div>