I assume that you've already got the form component in your app. Then, to send data to API, you need to do the following:
Create a JS class with same fields as your model in Django has. For example:
export class Book {
name: string;
description: string;
}
Create an instance of this class in your form component and connect its attributes to form fields. Example:
export class BookFormComponent implements OnInit {
constructor(private _bookService: BookService) {}
// ...
book: Book = new Book();
}
Also I've shown the constructor here to show that we are connecting to EventsService, which is responsible for communication with API.
In template: bind your inputs to your object attributes (see Angular guide to forms):
<form (ngSubmit)="onSubmit()" #bookForm="ngForm" id="bookForm">
<label for="bookName">Book name:</label>
<input type="text" name="name" id="bookName" maxlength="140"
required [(ngModel)]="book.name"/>
<label for="bookDescription">Description:</label>
<textarea form="bookForm" name="description" id="bookDescription" rows="3"
required [(ngModel)]="book.description"></textarea>
</form>
Create a method in your service which will send a POST request. It may look like this:
export class BookService {
_bookUrl = 'http://your.api.url/books-view'
addBook(book: Book) {
let headers = new Headers();
headers.append('Content-Type','application/json');
headers.append('X-CSRFToken', this.getCookie('csrftoken'));
return this.http.post(this._booksUrl, JSON.stringify(book),
{headers: headers})
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
}
_booksUrl is a URL of your view with list of books in Django REST Framework.
You may have problems with API not saving data because of you not being logged in. Adding Headers as seen above is the easiest workaround, but I suggest you to look for other options to authorize.
Call addBook() from your service in onSubmit inside the component:
onSubmit() {
this.addBook(this.book);
}
addBook(book: Book) {
let res = this._bookService.addBook(book)
.then(
result => res = result);
}
After those steps your Angular app should communicate with your Django REST API with no problems.
This is a simplified version of the project I'm doing. You may check the code on github (see event-form.component.ts and events.service.ts) to see the whole picture.