Identifier 'required' is not defined. '__type' does not contain such a member
Asked Answered
R

10

21

I need to declare this variable to type any? This shows up in my visual code editor in my HTML template.

enter image description here

product-form.component.html

<div class="row">

  <div class="col-md-6">
      <form #form="ngForm" (ngSubmit)="save(form.value)">

            <div class="form-group">
              <label for="title">Title</label>
              <input #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
              <div class="alert alert-danger" *ngIf="title.touched && title.invalid">
                Title is required.
              </div>
            </div>

            <div class="form-group">
                <label for="price">Price</label>
                <div class="input-group">
                  <span class="input-group-addon">$</span>
                  <input #price="ngModel" ngModel [(ngModel)]="product.price" name="price" id="price" type="number" class="form-control" required [min]="0">
                </div>
                <div class="alert alert-danger" *ngIf="price.touched && price.invalid">
                  <div *ngIf="price.errors.required">Price is required.</div>
                  <div *ngIf="price.errors.min">Price should be 0 or higher.</div>
                </div>
            </div>

            <div class="form-group">
                <label for="category">Category</label>
                <select #category="ngModel" ngModel [(ngModel)]="product.category" name="category" id="category" class="form-control" required>
                  <option value=""></option>
                  <option *ngFor="let category of categories$ | async" [value]="category.key">{{ category.payload.val().name }}</option>
                </select>
                <div class="alert alert-danger" *ngIf="category.touched && category.invalid">
                  Category is required.
                </div>
            </div>

            <div class="form-group">
                <label for="imageUrl">Image URL</label>
                <input #imageUrl="ngModel" ngModel [(ngModel)]="product.imageUrl" name="imageUrl" id="imageUrl" type="text" class="form-control" required url>
                <div class="alert alert-danger" *ngIf="imageUrl.touched && imageUrl.invalid">
                  <div *ngIf="imageUrl.errors.required">Image URL is required.</div>
                  <div *ngIf="imageUrl.errors.url">Please enter a valid URL.</div>
                </div>
            </div>

            <button class="btn btn-primary">Save</button>

          </form>
  </div>

  <div class="col-md-6">
      <div class="card" style="width: 20rem;">
          <img class="card-img-top" [src]="product.imageUrl" *ngIf="product.imageUrl">
          <div class="card-block">
            <h4 class="card-title">{{ product.title }}</h4>
            <p class="card-text">{{ product.price | currency: 'USD': symbol }}</p>
          </div>
        </div>
  </div>

</div>

product-form.component.ts

import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../../category.service';
import { ProductService } from '../../product.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/take';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {

  categories$;
  product: any = {};

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private categoryService: CategoryService,
    private productService: ProductService) {
    this.categories$ = categoryService.getCategories();

    let id = this.route.snapshot.paramMap.get('id');
    if (id) {
      this.productService.get(id).take(1).subscribe(p => this.product = p);
    }
  }

  save(product) {
    this.productService.create(product);
    this.router.navigate(['/admin/products']);
  }

  ngOnInit() {
  }

}

How do I remove this error? Functionality in the app doesn't seem to be effected. So from what I understand it compiles into valid JS. I was able to fix the objects by declaring it as "any"

I would be interested in learning how to setup an interface for this if possible.

Redcap answered 24/11, 2017 at 4:21 Comment(1)
Nowhere do we see what you have tried other than any. Also would be great if you could create a stackblitz that showcases this error :)Isolationism
V
39

There is a bug in angular. That compiler error will dissapear if you write that *ngIf like this:

          <div *ngIf="price.errors['required']">
Vapor answered 17/4, 2018 at 14:22 Comment(0)
C
27

try to add "?" after "price".

Like this:

<div *ngIf="price?.errors.required">Price is required.</div>
<div *ngIf="price?.errors.min">Price should be 0 or higher.</div>
Continuance answered 3/1, 2018 at 16:19 Comment(1)
worked for me. Just so I understand what it does: does it check if object is not null before accessing properties?Wilsey
V
13

I had same problem with my VS Code. I solved it only using !! before the condition.

Try:

    <div *ngIf="!!price.errors.required">Price is required.</div>
    <div *ngIf="!!price.errors.min">Price should be 0 or higher.</div>

More info: https://github.com/angular/vscode-ng-language-service/issues/126

Vaseline answered 21/11, 2018 at 0:0 Comment(1)
very nice answer thanks, I have the same issue with !!name?.errors?.maxlength where maxlength show Identifier 'maxlength ' is not defined. '__type' does not contain such a member into VS Code. after runing the code with issue on browser it is not showing any error but the maxlength does not work means : p class="form-control-feedback-text" *ngIf="name.errors?.maxlength && ( name.dirty || name.touched)">Name can not be more than 50 characters.</p> when i use !! then its work "What is the issue is it TS or any other issue".Manama
S
8
<div class="alert alert-danger" *ngIf="email.touched && !email.valid">
     <div *ngIf="email.errors['required']">Email is required</div>
     <div *ngIf="email.errors['minlength']">Email should be minimum {{ email.errors['minlength']['requiredLength'] }} characters</div>
     <div *ngIf="email.errors['maxlength']">Email should be maximum {{ email.errors['maxlength']['requiredLength'] }} characters</div>
     <div *ngIf="email.errors['pattern']">Email doesn't match the pattern.</div>
</div>
Scrofulous answered 23/7, 2018 at 12:0 Comment(0)
Y
5

Had similar error trying to access FormArray controls inside the FormGroup on the view using ngFor.

Some answers to this question worked partially, causing either compile errors or project build failure. For instance:

libraryForm.get('books') //compile error
libraryForm.controls['books'].controls' //build failure

Only below solution works for me so far:

libraryForm['controls']['books']['controls']

whole element:

<div [formGroupName]="i" *ngFor="let book of libraryForm['controls']['books']['controls'];let i = index">
Yanirayank answered 8/3, 2019 at 21:36 Comment(1)
Thanks mate, you saved my life! It works like a charm!Sclerenchyma
H
1

Using the hasError() method instead of errors property fixes it for me.
Use it like this:

 <div *ngIf="price.hasError('required')">Price is required.</div>
Haemoid answered 7/7, 2019 at 20:21 Comment(0)
P
0

You can just Add Question mark in-front of your property

  <label [attr.data-error]="Password.errors!=null?(Password?.errors.Required?'Required 
  field!':'Minimum 3 Characters Needed'):''">Password</label>
Pape answered 7/2, 2019 at 19:3 Comment(1)
@Ram Ghadiyaram Yeah Sure...My pleasure..... It represent nullable property as first time it may null so that you have to handle it in such a way.....ThanksPape
I
0

I had the same issue, y solved thanks to the answer from António César Júnior:

https://mcmap.net/q/592812/-identifier-39-required-39-is-not-defined-39-__type-39-does-not-contain-such-a-member by only using

   !!

<div *ngIf="submitted && f.username.errors">
    <p *ngIf="f.username.errors.required">Email is required</p>
    <p *ngIf="f.username.errors.email">The mail address is invalid</p>
</div>

working in a previous project, then changed to:

 <div *ngIf="submitted && !!f.username.errors">
   <p *ngIf="!!f.username.errors.required">Email is required</p>
   <p *ngIf="!!f.username.errors.email">The mail address is invalid</p>
 </div>
Ironworks answered 20/8, 2019 at 14:50 Comment(0)
C
0

Please check with this solution (for me works fine)!

<div class="alert alert-danger" *ngIf="username.touched && username.invalid">
  <div *ngIf="username.errors['required']">Username are required!</div>
  <div *ngIf="username.errors['minlength']">Username should be minimum {{ username.errors['minlength'].requiredLength }} characters!</div>
  <div *ngIf="username.errors['cannotContainSpace']">Username cannot contains spaces!</div>
</div>
Colliery answered 28/9, 2019 at 21:38 Comment(0)
R
0

There does seem to be some issue mentioned in the docs:

Sometimes a binding expression triggers a type error during AOT compilation and it is not possible or difficult to fully specify the type. To silence the error, you can use the $any() cast function to cast the expression to the any type as in the following example

So you could do:

$any(price.errors).required

Rambouillet answered 7/12, 2020 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.