[英]Property 'name' does not exist on type 'ContactComponent'
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'.".我正在尝试通过 ngModel 验证 angular 表单中的必填字段,但我收到错误消息“属性‘名称’在类型‘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" class="inputColor">{{ contact.name }}</div>
<input
[ngStyle]="{ border: '1px solid #dee1e5' }"
*ngIf="isEditing"
class="inputColor form-control"
type="text"
id="name"
name="name"
[(ngModel)]="form.name"
required
#name="ngModel"
/>
<div *ngIf="name.invalid" class="p-1 bg-red-300 text-red-800 Rounded">
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'.注意:只有当我尝试验证它时,绑定才能正常工作抛出错误“错误:src/app/contacts/contact/contact.component.html:27:19 - 错误 TS2339:属性‘name’不存在于输入“ContactComponent”。
27 <div *ngIf="name.invalid" class="p-1 bg-red-300 text-red-800 Rounded">" 27 <div *ngIf="name.invalid" class="p-1 bg-red-300 text-red-800 Rounded">"
the problem is there: just add the question mark to check is the name exists or not into the contact问题在那里:只需添加问号即可检查该名称是否存在于联系人中
<div *ngIf="!isEditing" class="inputColor">{{ contact?.name }}</div>
you can see the code here:你可以在这里看到代码:
https://stackblitz.com/edit/angular-ivy-bnlkhe?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts https://stackblitz.com/edit/angular-ivy-bnlkhe?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts
So you put the *ngIf
within your template var #name
所以你把
*ngIf
放在你的模板 var #name
中
<input *ngIf="isEditing" #name="ngModel" />
<div *ngIf="name.invalid" class="p-1 bg-red-300 text-red-800 Rounded">
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.比方说,
isEditing = false
,这意味着将没有输入字段=>没有绑定name
变量的模板=>因此,错误:不存在名称。
The solution: wrap the whole content under *ngIf
.解决方案:将整个内容包装在
*ngIf
下。 Something like this:是这样的:
<ng-content *ngIf="isEditing">
<input #name="ngModel" />
<div *ngIf="name.invalid" class="p-1 bg-red-300 text-red-800 Rounded">
Address is required
</div>
</ng-content>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.