Reputation: 766
I created this simple form form1.component.html in Angular
<form #personForm="ngForm" (ngSubmit)="submitForm(personForm)" novalidate>
<div>
<label> Enter First Name </label>
<input
type="text"
[(ngModel)]="person.firstName"
required
pattern="[A-Za-z]*"
#firstName="ngModel"
name="fName"
/>
</div>
<div>
<button type="submit" class="btn-solid">Submit</button>
<button type="button" (click)="clearForm(personForm)">Reset</button>
</div>
</form>
The ts file form1.component.ts is as follows
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form1',
templateUrl: './form1.component.html',
styleUrls: ['./form1.component.css']
})
export class Form1Component implements OnInit {
person!: {};
constructor() { }
ngOnInit(): void {
this.person = {
firstName: 'John',
lastName: 'Black'
};
}
submitForm = (form: any) => {
}
clearForm = (form: any) => {
form.reset();
form.submitted = false;
}
}
When I run ng serve in VS Code, I get following error
Error: src/app/components/form1/form1.component.html:6:33 - error TS2339: Property 'firstName' does not exist on type '{}'.
6 [(ngModel)]="person.firstName"
~~~~~~~~~
src/app/components/form1/form1.component.ts:5:16
5 templateUrl: './form1.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component Form1Component.
I tried to initialize the person class in constructor, but still gives the same error
Upvotes: 2
Views: 14057
Reputation: 18909
You have a wrong type declaration
Change the declared type in your component
export class Form1Component implements OnInit {
person!: { firstName: string; lastName: string };
Otherwise you can make it even more lighter by
export class Form1Component implements OnInit {
person!: any;
Also if you don't want to duplicate your code of { firstName: string; lastName: string }
create an interface type
interface Person{
firstName: string;
lastName: string;
}
and then you can use it in multiple places like
export class Form1Component implements OnInit {
person!: Person;
doSomething(person: Person) {
...
}
Upvotes: 2
Reputation: 1852
While the form is incomplete (since it only has first name) you can declare an interface to use throughout your component. This will give you better type security instead of having any
scattered through the component.
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
interface Person{
firstName: string;
lastName: string;
}
@Component({
selector: 'app-form1',
templateUrl: './form1.component.html',
styleUrls: ['./form1.component.css']
})
export class Form1Component implements OnInit {
person: Person;
constructor() { }
ngOnInit(): void {
this.person = {
firstName: 'John',
lastName: 'Black'
};
}
submitForm = (form: NgForm) => {
this.person = form.value as Person;
}
clearForm = (form: NgForm) => {
form.reset();
form.submitted = false;
}
}
Upvotes: 0