Angular4: Pass data from parent to child component (part 5)

Set  up an ng project,

$ ng new angularcomponentpassing

Create a new component,

$ ng g c cockpit

File: cockpit.component.ts

import { Component, OnInit, Input } from ‘@angular/core’;

@Component({
selector: ‘app-cockpit’,
templateUrl: ‘./cockpit.component.html’,
styleUrls: [‘./cockpit.component.css’]
})
export class CockpitComponent implements OnInit {
@Input(‘srvElement’) element: {name: string, id: number;}
constructor() { }

ngOnInit() {
}

}

Note: ‘srvElement’ is an alias for ‘element’ and can be left out above like this,

@Input() element: {name: string, id: number;}
constructor() { }

File: cockpit.component.html

<hr>
<p>
cockpit works!
</p>
<p><strong>Name:</strong> {{ element.name }}, <strong>id:</strong> {{ element.id }}</p>

File: app.component.ts

import { Component } from ‘@angular/core’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
title = ‘app works!’;
serverElements = [{name: ‘John’, id: 8}, {name: ‘Matt’, id: 10}];
}

File: app.component.html

<h1>
{{title}}
</h1>
<app-cockpit *ngFor=”let serverElement of serverElements” [srvElement]=”serverElement”>hello</app-cockpit>

If the alias for ‘element’, which is ‘srvElement’ is not used then the above line should be,

<app-cockpit *ngFor=”let serverElement of serverElements” [element]=”serverElement”>hello</app-cockpit>

Part 4: Django CRUD, Create

Continued from Part 3: Django CRUD, Display Models

Full code on https://github.com/shanegibney/djangoCRUD

Before starting this section it would be a good idea to include Bootstrap to make use of the classes in the html, but it is not necessary. It is only to make it look nice! To do that add the following lines inside the head tags of index.html.

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

CRUD is an acronym for Create, Read, Update and Delete. First we would like to make a form and send this data to the database or our ‘Members’ model. This will be the Create part of CRUD.
First we need to create a form. But to do that we need to tell Django which fields from the model members to put in the form. Create a new file called ‘forms.py’ and place it in the same place as ‘models.py’.

‘forms.py’ must import forms from Django and your model Members from models. This done by adding to the top of ‘forms.py’

from django import forms
from .models import Members

We create a new model here for the form, but it takes from the current model ‘Members’. This is done with a ‘class Meta’ and we can choose which fields from ‘Members’ we want in the form,

 class MemberForm(forms.ModelForm):
    class Meta:
        model = Members
        # which fields to put in form
        fields = ('first_name', 'last_name', 'description')

We need a link to the url which we are calling ‘member_new’. So in urls.py add in,

url(r'^post/new/$', home.member_new, name='member_new'),

This gives the url a name of ‘member_new’. To get to this url you need a hyper-link in ‘index.html’,

<a href="{% url 'member_new' %}">Add a post</a>

This causes Django to look in urls.py for a url named ‘member_new’ where it is associated with the url ‘post/new/’. Note that is not actually a path called ‘post/new/’. Then Django looks through all these urls again to find the url ‘post/new/’ and see what view it is associated with. In this case the view is ‘home.members_new’. Now will create this view in ‘views.py’,

def member_new(request):

Django first checks if the “POST” method exists. Of course it doesn’t because we haven’t used a form yet. Therefore this section is ignored and Django carries on to the ‘else’.

    if request.method == "POST":
        ..... we will come here after the form is sent ......
    else:
        form = MemberForm()
    return render(request, 'member_edit.html', {'form': form})

The ‘MemberForm’ which we created earlier and has the fields in it is now passed to ‘form’, and the last line renders ‘member_edit.html’ by sending it {‘form’: form}.
We need to create ‘member_edit.html’ in the templates folder. This file will extend ‘index.html’. To create the form itself we only need to wrap in form tags {{ form.as_p }} like this,

{% extends 'index.html' %}

{% block content %}
    <th1>Member form&lt/h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}in the form
        <button type="submit" class="save btn btn-default">Save<button>
    <form>
{% endblock %}

This creates a block called ‘content’ which will be placed by Django in ‘index.html’ if we add to ‘index.html’ the following,

{% block content %}
{% endblock %}

When you run the server you should have a link on the ‘index.html’ page to a form with fields. But you won’t be able to submit because we haven’t finished writing the view ‘member_new’, which is where this form will submit to.

But this time “POST” does exist and so the if statement is not ignored. We need to fill this view in so that completed it looks like this,

def member_new(request):
    if request.method == "POST":
        form = MemberForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = MemberForm()
    return render(request, 'member_edit.html', {'form': form})

Note that we are using ‘redirect’, this needs to be imported by placing the following line at the top of ‘views.py’,

from django.shortcuts import redirect

You can see this passes everything in “POST” to form and validates ‘form’ with ‘.is_valid’. The line ‘form.save…’ saves the form data to memory, not to the database yet. ‘post.save()’ does that. Therefore this is where a new row is added to the database or where the actual ‘create’ in CRUD happens. The next line redirects us to the ‘init’ view. Which recreates the home page and the table of data from the ‘Members’ model.
This concludes the ‘C’ or ‘create’ in CRUD and we have already dealt with the ‘R’ for ‘read’.

Part 5: Django CRUD, Delete

Simple Python into HTML

The following Python code will find instances of {body} in a file template.html and replace it with a string. Then a new file index.html is created with this change.

generate.py

with open('template.html','r') as template_file:
    template = template_file.read()

content = template
tokens = {'body': 'Body stuff can go here'}
replaced = 'Body stuff can go here.'
content = content.replace('{' + 'body' + '}', replaced)

with open('index.html', 'w') as content_file:
     content_file.write(content)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
    <div><p>{body}</p></div>
</html>