Home > Net >  Property 'name' does not exist on type 'ContactComponent'
Property 'name' does not exist on type 'ContactComponent'

Time:11-19

I'm trying to validate a required field in an angular form through the ngModel but I get the error "Property 'name' does not exist on type 'ContactComponent'.". I have seen some implementation examples but I do not see where my error is, below I share a fragment of the template and the component:

template:

<div>
  <label for="name">Name</label>
  <div *ngIf="!isEditing" >{{ contact.name }}</div>
  <input
    [ngStyle]="{ border: '1px solid #dee1e5' }"
    *ngIf="isEditing"
    
    type="text"
    id="name"
    name="name"
    [(ngModel)]="form.name"
    required
    #name="ngModel"
  />
  <div *ngIf="name.invalid" >
    Address is required
  </div>

Component:

export class ContactComponent {
@Input() contact: Contact = {} as Contact;

 isEditing: Boolean = false;

form: Contact = {
name: '',
address: '',
phoneNumber: '',
email: '',
};

edit = () => {
this.isEditing = true;
} ;

remove = () => {};

save = () => {
console.log('on submit', this.form);
this.isEditing = false;
};
}

Note: The binding it is working correctly only when I try to validate it throws the error "Error: src/app/contacts/contact/contact.component.html:27:19 - error TS2339: Property 'name' does not exist on type 'ContactComponent'.

27 <div *ngIf="name.invalid" >"

CodePudding user response:

the problem is there : just add the question mark to check is the name exists or not into the contact

<div *ngIf="!isEditing" >{{ contact?.name }}</div>

you can see the code here :

https://stackblitz.com/edit/angular-ivy-bnlkhe?file=src/app/app.component.html,src/app/app.component.ts

CodePudding user response:

So you put the *ngIf within your template var #name

<input *ngIf="isEditing" #name="ngModel" />
  <div *ngIf="name.invalid" >
    Address is required
  </div>

let say, isEditing = false, which means there gonna be no input field => no template to bind the name variable => hence, the error: No name exist.

The solution: wrap the whole content under *ngIf. Something like this:

<ng-content *ngIf="isEditing">

      <input #name="ngModel" />
      <div *ngIf="name.invalid" >
        Address is required
      </div>
</ng-content>
  • Related