0

I'm learning Angular2, and I'm trying to check if a text field inside my component is valid or not. I built a component called MyUpload and I'm calling it inside a modal component. On my modal, I'm trying to verify if a field (myField) inside it is valid or not. I tried to do something like this:

<my-upload #upload [maxSize]="10000" [multiple]="true"></my-upload>
<textarea name="comment" ... ></textarea>

<button ... 
  [disabled]="f.form.valid && upload.form.myField.valid" ...>Save</button>

But I get:

Cannot read property 'myField' of undefined

I also tried upload.form.control.myField.valid, but its not working. It seems that the #upload is not referencing the form inside my component.

How can I do that?

aseolin
  • 1,184
  • 3
  • 17
  • 35

1 Answers1

0

Look at the answer here for extended explanation. What does Angular 2 hashtags in template mean?

In short, this means that the # reference is an html reference and includes only the html attributes of the reference, and not the html members of the underlying component.

The upload.form means that there is a form attribute in your html on the my-upload html element. There isn't, so it's null.

To use the component like this, it should implement a custom form control and be handled as you should handle an input. You can with around it, but the form must be declared in the child component and some null checking should occur as per the comment in the question.

Check ControlValueAccessor for custom controls. Check https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html for a nice guide.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61