Reputation: 73
So, I've worked extensively with AngularJS but I'm new to Angular 8. Now my problem is related to the two way data binding of Angular. I've already searched stackoverflow but couldn't find proper solution and that's why I'm posting this. My code contains an external data object as follows
export class Contact {
name: string;
email: string;
phone: string;
message: string;
}
I've imported the above in my component where I've to use this class object. The relevant code from my component is:
import { Contact } from '../contactDetails';
contact: Contact;
processForm(){
const allInfo=`My name is ${this.contact.name}. My email is ${this.contact.email}. My phone number is
${this.contact.phone}. My message is ${this.contact.message}`;
alert(allInfo);
}
The relevant code of the corresponding template is:
<form class="contact-bg" id="contact-form" name="contact-form">
<input type="text" name="name" class="form-control" placeholder="Your Name*"
[ngModel]="contact?.name" (ngModel)="contact.name"/>
<input type="email" name="email" class="form-control" placeholder="Your E-mail*"
[ngModel]="contact?.email" (ngModel)="contact.email"/>
<input type="text" name="phone" class="form-control" placeholder="Phone Number"
[ngModel]="contact?.phone" (ngModel)="contact.phone"/>
<textarea name="message" class="form-control" placeholder="Your Message*" style="height:120px"
[ngModel]="contact?.message" (ngModel)="contact.message"></textarea>
<button (click)="processForm(contact)" id="submit" type="submit" name="submit">Send</button>
</form>
The problem I'm facing is when I try to submit my form after filling all details it gives me error:
ERROR TypeError: Cannot read property 'name' of undefined at ContactComponent.processForm (contact.component.ts:25) at Object.eval \[as handleEvent\] (ContactComponent.html:47) at handleEvent (core.js:38098) at callWithDebugContext (core.js:39716) at Object.debugHandleEvent \[as handleEvent\] (core.js:39352) at dispatchEvent (core.js:25818) at core.js:37030 at HTMLButtonElement.<anonymous> (platform-browser.js:1789) at ZoneDelegate.invokeTask (zone-evergreen.js:391) at Object.onInvokeTask (core.js:34182)][1]][1]
Attached is the screenshot for the same.
I'm sure that there's some syntactical error, but I'm not able to find one. Can someone please help me to find out the same? Thanks in advance.
P.S.: I've only given the relevant code snippet from my component and template and not the complete code. Please assume that the boilerplate code is already there.
Upvotes: 1
Views: 4353
Reputation: 67
syntax is [(ngModel)] = "contact?.message" or syntax is [(ngModel)] = "contact.message"
check this https://stackblitz.com/edit/angular-gdzvam?file=src%2Fapp%2Fapp.component.html
Upvotes: 0
Reputation: 857
use [(ngModel)]="contact.name"
for bindings and instantiate contact object while declaring
contact: Contact = new Contact();
Upvotes: 3