我尝试通过ngModel验证角形表单中的必填字段,但收到错误“Property 'name' does not exist on type 'ContactComponent'."。我看过一些实现示例,但没有发现错误所在,下面我分享了模板和组件的一个片段:
模板:
<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>
组成部分:
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;
};
}
注意:只有当我尝试验证绑定时,它才能正常工作,并抛出错误“Error:联系人/联系人/联系人.组件.html:27:19 -错误TS 2339:类型“ContactComponent”上不存在属性“name”。
27〈div *ngIf=“名称.无效”class=“p-1 bg-红色-300文本-红色-800四舍五入”〉”
1条答案
按热度按时间l2osamch1#
问题就在这里:只需在联系人中添加问号来检查该名称是否存在
你可以在这里看到代码:
https://stackblitz.com/edit/angular-ivy-bnlkhe?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts