-
Notifications
You must be signed in to change notification settings - Fork 27.1k
Template variable is not accesible for validation when using NgFor #13974
Description
I'm submitting a ... (check one with "x")
[x] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
Current behavior
When dynamically creating a group of radio buttons using NgFor and then creating a template variable pointing to an instance of the NgModel directive for validation, the variable is never set.
@Component({
selector: 'rio-app',
template: `
<form #myForm="ngForm">
<label *ngFor="let gender of genders">
{{ gender }}:
<input type="radio" name="gender" [value]="gender"
ngModel required #myGender="ngModel"
/>
</label>
<div [hidden]="!myGender.hasError('required')">
The gender is required
</div>
</form>
`
})
export class AppComponent {
genders = ['Male', 'Female']
}When executing this code, I get the following error in the browser's console:
Cannot read property 'hasError' of undefined
Expected behavior
The template variable should be defined and being able to be used for validation.
If instead of using NgFor to generate the group of radio buttons I hardcode the options, the app works.
@Component({
selector: 'rio-app',
template: `
<form #myForm="ngForm">
<label>
Male:
<input type="radio" name="gender" value="Male"
ngModel required #gender="ngModel"
/>
</label>
<label>
Female:
<input type="radio" name="gender" value="Female"
ngModel required #gender="ngModel"
/>
</label>
<div [hidden]="!gender.hasError('required')">
The gender is required
</div>
</form>
`
})
export class AppComponent {}Minimal reproduction of the problem with instructions
See plunker above
What is the motivation / use case for changing the behavior?
To be able to have a standard way to handle validation when using NgFor or hardcoding options
Please tell us about your environment:
Plunker
-
Angular version: 2.0.X
Angular 2.4.1 -
Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
Chrome 55 on MacOS Sierra
- Language: [all | TypeScript X.X | ES6/7 | ES5]
Typescript
- Node (for AoT issues):
node --version=