I'm developing a web application using Angular 6. I would like to create some custom components that are inspired by the components of HTML input. For example:
CustomComponent.ts (typescript)
@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 (template)
<input type="text"
[attr.name]="name"
[required] = "isRequired"
/>
I have this problem. Suppose we use my component in this template:
<form #myForm="ngForm" ngNativeValidate>
<custom-component
name="myName"
[isRequired] = true
ngModel
></custom-component>
<button type="submit" (click)="method()">Click</button>
The required attribute it's initialized correctly in the <input type="text/> (wrapped component of <custom-component>). The problem is this (it's an Angular problem!): in this code of usage:
method() {
console.log(this.myForm.valid);
}
The object myForm.valid (where myForm is associated with #myForm in the previous template) return always the true value, even if nothing is entered in the text field. This behavior is wrong: I would like this value to be false if I do not insert anything in the required field.