Reputation: 3016
I want to bind a Company object from my component to my view. This was easy in AngularJS, but I get an error when I do this in Angular 2.
View
<input type="text" class="form-control" [(ngModel)]="company.name"
placeholder="Company Name" required>
<input type="text" class="form-control" [(ngModel)]="company.address1"
placeholder="Address Line 1" id="address1" required>
<button class="btn btn-primary pull-right next-btn" (click)="show()">Next</button>
Component:
company: Company;
constructor(
private router: Router
) { }
ngOnInit() { }
show() {
console.log(this.company);
}
error:
TypeError: Cannot read property 'name' of undefined
Upvotes: 1
Views: 13988
Reputation: 549
<input type="text" value="{{ company.name | async}}" placeholder="filter by server status" [(ngModel)]="company.name">
Upvotes: 0
Reputation: 3016
As @Rahul said I had to import NgForm from the @angular/forms module for it to work
Upvotes: 1
Reputation: 76
You are trying with Template Driven forms, If you are interested on Reactive Form please see the below site
https://toddmotto.com/angular-2-forms-reactive
Good luck!
You can use the below code for your (Template Driven Form) reference.
<code>
import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app',
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
<div>Username: <input type="text" name="username" ngModel></div>
<div>SSN: <input type="text" name="ssn" ngModel></div>
<div>Password: <input type="password" name="password" ngModel></div>
<div>Confirm password: <input type="password" name="pconfirm" ngModel></div>
<button type="submit">Submit</button>
</form>
`
})
class AppComponent {
onSubmit(formData) {
console.log(formData);
}
}
@NgModule({
imports : [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap : [ AppComponent ]
})
class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
</code>
Upvotes: 1
Reputation: 15279
If you are using ngModel
out of the form then you must set options to [ngModelOptions]="{standalone: true}"
, if you have from, then you must set name
attribute for each control.
Upvotes: 1