我正在使用Range6开发一个web应用程序,我想要创建一些受HTML输入组件启发的定制组件。例如:
CustomComponent.ts (打字稿)
@Component({
selector: 'custom-component',
templateUrl: './custom-component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => InputTextComponent)
}
]
})
export class CustomComponent {
@Input() name: string;
@Input() isRequired: boolean;
}CustomComponent.html (模板)
<input type="text"
[attr.name]="name"
[required] = "isRequired"
/>我有这个问题。假设我们在这个模板中使用了我的组件:
<form #myForm="ngForm" ngNativeValidate>
<custom-component
name="myName"
[isRequired] = true
ngModel
></custom-component>
<button type="submit" (click)="method()">Click</button>required属性在<input type="text/> (<custom-component>的包装组件)中被正确初始化。问题是(这是一个角度问题!):在这个用法代码中:
method() {
console.log(this.myForm.valid);
}对象myForm.valid (其中myForm与上一个模板中的#myForm相关联)总是返回true值,即使文本字段中没有输入任何内容。此行为是错误的:如果不在所需字段中插入任何内容,我希望此值为false。
发布于 2018-11-13 16:01:07
若要向自定义输入组件添加验证,应向提供程序添加以下内容:
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => InputTextComponent),
multi: true
}您必须在InputTextComponent中实现默认方法:
validate(control: AbstractControl): ValidationErrors | null {
return null;
}如果您使用用您的()实现的writeValue()方法正确地更新了组件中名为writeValue值NG_VALUE_ACCESSOR的属性,然后确保调用(可以通过在默认输入上实现更改事件来实现此操作):
this.propagateChange(this.value);最后,将isRequired输入更改为默认所需的属性。
@Input() required: boolean;您的NgModel现在应该正确更新。
编辑:避免使用必需的(但是这是正确的方法)。在验证方法中放置以下代码:
validate(control: AbstractControl): ValidationErrors | null {
return this.isRequired && this.value.length === 0 : { required: true } : null;
}当角运行它自己的验证时,它会调用这个方法。当此方法返回除null以外的任何内容时,该对象将添加到FormControl & NgModel中的errors属性中。
这是一个巨大的主题,有一些伟大的文章,适当地解释了这一切。然而,正如人们所问的那样,这应该能解决这个问题。
发布于 2018-11-13 15:58:55
您应该检查表单是否脏,是否有效。所以两者都必须是真的。否则它就表明它没有被改变。
https://stackoverflow.com/questions/53284663
复制相似问题