Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support optional chaining in template #149

Closed
marcelnem opened this issue Aug 18, 2017 · 70 comments
Closed

Support optional chaining in template #149

marcelnem opened this issue Aug 18, 2017 · 70 comments
Assignees
Labels

Comments

@marcelnem
Copy link

marcelnem commented Aug 18, 2017

in 0.1.4 on Windows 10

errors?.required is highlighted as an error

<form (submit)="onSubmit()" novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" [(ngModel)]="user.name" name="name" #userName="ngModel" minLength="2" required>
        <div *ngIf="userName.touched && userName.errors?.required" class="alert alert-danger">Name is required</div>
    </div>
    <div class="form-group">
        <label for="name">Email</label>
        <input type="text" class="form-control" [(ngModel)]="user.email" name="email" #userEmail="ngModel" required>
    </div>
    <div class="form-group">
        <label for="age">Phone</label>
        <input type="number" class="form-control" [(ngModel)]="user.phone" #userPhone="ngModel" name="phone" minlength="10">
    </div>
    <input type="submit" value="Submit" class="btn btn-success">
</form>

image

@Kurtz1993
Copy link

Also happening on OS X 10.11.6 (El Capitan).

OS: OS X 10.11.6
Extension version: 0.1.4
VS Code version: 1.15.1

@chuckjaz chuckjaz added the bug label Aug 29, 2017
@DuanTranHuy
Copy link

I also got this problem on Window 10 x64
Extension version 0.1.7
VS Code version 1.15.1
Please fix it soon

@matthew-ch
Copy link

Same problem here.
Error is: 'Identifier 'errors' is not defined. 'NgModel' does not contain such a member'.

OS: macOS 10.13
Extension: 0.1.7
VS Code: 1.16.1
Angular: 4.4.3
Typescript: 2.5.2

@imomer
Copy link

imomer commented Oct 3, 2017

Same problem! Any solution?

@imomer
Copy link

imomer commented Oct 4, 2017

Should I import it in the app.module or in my component where the form is exist?

@PBartrina
Copy link

PBartrina commented Oct 9, 2017

The @angular/forms imports mentioned by @VladBozhinovski won't solve it.
Kind of related: #179

@imomer
Copy link

imomer commented Oct 9, 2017

Yeah didn't work me either...

@devmrh
Copy link

devmrh commented Nov 22, 2017

i have same problem .... any solution ?

@SlashD9
Copy link

SlashD9 commented Dec 3, 2017

Same Issue, has anyone found a fix?

@pahofmann
Copy link

Same issue here. Any ideas yet?

@GhanemJR0
Copy link

I also got this problem any solutions

@FreekMencke
Copy link

Same here.

@mezubeen
Copy link

it seems like I'm not alone :)

@DuanTranHuy
Copy link

So many people got this problem. You guys can prevent it like 'email?.error.required'

@niblux
Copy link

niblux commented Jan 6, 2018

@Duanthse03268 this worked by removing the red line error but still get the following console error, any idea why ?

FoodFormComponent.html:9 ERROR TypeError: Cannot read property 'minlength' of undefined at Object.eval [as updateDirectives] (FoodFormComponent.html:10) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13056) at checkAndUpdateView (core.es5.js:12236) at callViewAction (core.es5.js:12601) at execComponentViewsAction (core.es5.js:12533) at checkAndUpdateView (core.es5.js:12242) at callViewAction (core.es5.js:12601) at execComponentViewsAction (core.es5.js:12533) at checkAndUpdateView (core.es5.js:12242) at callWithDebugContext (core.es5.js:13456)

@DuanTranHuy
Copy link

Make sure u import
import { FormsModule, Validators } from '@angular/forms';

@joonashak
Copy link

joonashak commented Jan 8, 2018

None of the solutions in this thread resolve the issue. I made an example as simple as possible to make sure nothing else was messing it up:

screen shot 2018-01-08 at 22 56 53

FormModule and Validators have been imported from @angular/forms. I also tested this solution by @Duanthse03268, and not only does it not resolve the red line issue, it also causes an error in console when the state of myField changes (TypeError: Cannot read property 'required' of null) if used without the '?' after 'errors'.

My implementation works without errors in the browser but retains the (supposedly incorrect) red line in editor (VSCode). Gists of the files in question (everything else you can simply 'ng new...' to reproduce):

app.module.ts
app.component.ts
app.component.html

Versions:

Extension: 0.1.7
VSCode: 1.19.1
Angular CLI: 1.6.3
Node: 9.2.1
OS: macOS 10.12.6
Angular: 5.1.3
Chrome: 63.0.3239.84

@DuanTranHuy
Copy link

Why did not you try to use 'myfield?.error.required' .

@joonashak
Copy link

I did try it, just as I wrote in my previous comment: "not only does it not resolve the red line issue, it also causes an error in console when the state of myField changes (TypeError: Cannot read property 'required' of null)".

So, to elaborate, 'myField?.errors.required' does not work and causes the above error message to be displayed in console. The '?' has to be written after 'errors' in order to have this code work in browser without error message, yet does not solve the original issue of incorrect red line in editor.

@Rawr421
Copy link

Rawr421 commented Jan 10, 2018

This is extremely annoying as the red lines are there still but the functionality works. I agree with joonashak as the solutions presented do not work and trying both formats do not resolve the issue.

@Ahnset
Copy link

Ahnset commented Jan 18, 2018

this worked for me: <div *ngIf="clientFirstName?.errors?.required

I hope it helps you.

@brunobertechini
Copy link

Only workarounds :(

@neha16k
Copy link

neha16k commented Feb 6, 2018

IntelliJ throws the same error for me. But the implementation works even with the errors in the browser. Workaround by @Ahnset worked for me. Would like to know what is this syntax and how is it working now?

@adickenscheidt
Copy link

I found that this error appears every time you reference a property which is defined as 'any'. Another workaround is using the bracket property annotation, clientFirstName?.errors['required'] which is also pretty stupid.

@Nomadzy
Copy link

Nomadzy commented Feb 23, 2018

Its getting worst, with the latest update of vscode, my file tree has become more like a christmas tree 🎄

@ghost
Copy link

ghost commented Feb 27, 2018

@adickenscheidt thank you for the workaround. Works great, agree dumb for now.

@mikesun23
Copy link

@boban984
this is the winner solution and explanation.

@thw0rted
Copy link

I was glad to find the hasError() method discussed here, it's certainly the clearest way to show the intent of the template conditional and I think I'll try to use it exclusively going forward.

However... nobody is addressing the root cause of the problem, and it's been an issue with the language service for something like a year now. The errors property has a key index signature ([key: string]: any) which means that in TS code, the statement myControl.errors.anythingYouLike will compile cleanly, no matter what strict-mode flags you have set. This is correct, because the entire point of having an index signature like that is to be able to create arbitrary properties at runtime, and access them by either dot-notation or index-notation. The language service allows index-notation, which is why control?.errors['required'] works, but flags dot-notation as incorrect, which is an error.

@Credo-Zhao
Copy link

Credo-Zhao commented Oct 7, 2018

three solutions:

<span *ngIf=" username.errors['email']">must be email</span>

<span *ngIf="!!username?.errors.email">must be email</span>

<span *ngIf="username.hasError('email')">must be email</span>

I like the third best

@vaibhavphutane
Copy link

@boban984 Great solution and explanation

@makitocode
Copy link

thnks, works for me!. 👍🏼
i hate view Errors on console 😬

@marlonpatrick
Copy link

marlonpatrick commented Nov 21, 2018

Hello try it like this.
Form.hasError('required');

This was the most elegant solution, and really works for all cases: myForm.hasError('required', 'myField').

Thanks @antonheck

@isidoreduc
Copy link

isidoreduc commented Feb 5, 2019

Hello try it like this.
Form.hasError('required');

This was the most elegant solution, and really works for all cases: myForm.hasError('required', 'myField').

It works, but the best solution based on simplicity was offered by @boban984: "myField.hasError('required')". :)

@bePericon
Copy link

bePericon commented Feb 17, 2019

I solved this problem in this way:

  • example.component.ts:
this.myForm = this.formBuilder.group({
      field: ['', [Validators.required, Validators.maxLength(10)]]
});

get getField() { return this.myForm.get('field'); }
  • example.component.html:
<div *ngIf="getField.errors" class="invalid-feedback">
  <div *ngIf="getField.hasError('required')"> Text required </div>
  <div *ngIf="getField.hasError('maxlength')"> Text maxLength </div>
</div>

I hope to be helpful.

@andrecontdi
Copy link

Perfect @bePericon this works for me!
Thanks!

@sohana08
Copy link

sohana08 commented Apr 8, 2019

<input type="text" formControlName="name" class="form-control" placeholder="Full name"> <div *ngIf="submitted && f['name'].errors" class="alert alert-danger"> <div *ngIf="f['name'].errors.required">Full Name is required</div> </div>
This worked for me in Angular 7

@JounQin
Copy link

JounQin commented Jun 15, 2019

So after two years, it has not been fixed? 🤣
related: #110

@boban100janovski
Copy link

So after two years, it has not been fixed? 🤣
related: #110

It's not a bug, it's exactly the way it should work

@dtromblee
Copy link

If this is expected functionality, can the documentation be updated? (see here for one example).

This clearly infers the raw property accessors of ngModel can be used, where this thread has established they definitely cannot.

@thw0rted
Copy link

thw0rted commented Jul 25, 2019

Actually is it fixed? I switched to hasError ages ago, but now I'm trying and failing to reproduce the error. myControl.errors.maxlength doesn't generate any red squiggly for me. This is with language service extension 0.801.1, which uses v8.1.x of the library, if that helps.

@dtromblee
Copy link

dtromblee commented Jul 25, 2019

@thw0rted so, upon retest with myControl.errors.required and .pattern and (realized I missed the required attribute on the input tag, which was causing a bigger failure), they don't quite work.

Required mostly works, though there were some odd errors that popped up (missed capturing them and they're inconsistent unfortunately), and pattern fires when the pattern is wrong but doesn't seem to update when the pattern's correct.

Also, I have the same vsCode language extension, and I still see squigglies strangely.

Going to stick with .hasError solution for the moment, and probably would still recommend the docs get updated, at least to have that as a clearer/best practice use.

@Angelo191
Copy link

I found that this error appears every time you reference a property which is defined as 'any'. Another workaround is using the bracket property annotation, clientFirstName?.errors['required'] which is also pretty stupid.

This removed the errors for me. For reference, the code worked even when the errors were outlined, I just don't like seeing red lines in my code.

@shiftgeist
Copy link

shiftgeist commented Aug 9, 2019

Yes putting in the key as a string removes the red lines.

But you lose features like correct spelling and auto-completion with this.

@teebszet
Copy link

teebszet commented Sep 24, 2019

in addition to using hasError(), accessing a form's child control should use get() rather that dot access. e.g.

class MyComponent {
  form: FormGroup;
}

with lines like this in the template :

<app-errors [control]="form.controls.email">

Error message :

Identifier 'email' is not defined. '__type' does not contain such a member

solution would be:

<app-errors [control]="form.get('email')">

@kyliau kyliau changed the title errors?.required highlighted as error Support optional chaining in template Nov 25, 2019
@Chrisssel
Copy link

Same issue.

f.email.errors.email.required Fails
!!f.email.errors.email.required Fails
f.email?.errors.email.required Fails
f?.email?.errors.email.required Fails
f.email.error.['required'] Fails
f.email?.error.['required'] Fails

This worked for me:

f['email'].errors.required

@ayazhafiz
Copy link
Member

Should be fixed with angular/angular#33884.

@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Feb 18, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.