WADF LAB Experiments
WADF LAB Experiments
By default, the CLI command ng new my-app creates a workspace folder named "my-app" and generates
a new application skeleton in a src/ folder at the top level of the workspace. A newly generated application
contains source files for a root module, with a root component and template.
Files at the top level of src/ support testing and running your application. Subfolders contain the
application source and application-specific configuration.
APPLICATION
PURPOSE
SUPPORT FILES
Inside the src folder, the app folder contains your project's logic and data. Angular components, templates,
and styles go here.
SRC/APP/ FILES PURPOSE
Creating a component
The best way to create a component is with the Angular CLI. You can also create a component manually.
Although the Angular CLI is the best way to create an Angular component, you can also create a
component manually. This section describes how to create the core component file within an existing
Angular project.
@Component({
})
selector: 'app-component-overview',
})
Define the HTML template that the component uses to display information. In most cases, this template
is a separate HTML file.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})
Select the styles for the component's template. In most cases, you define the styles for your component's
template in a separate file.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
styleUrls: ['./component-overview.component.css']
})
Add a class statement that includes the code for the component.
To define a template as an external file, add a templateUrl property to the @Component decorator.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})
To define a template within the component, add a template property to the @Component decorator that
contains the HTML you want to use.
@Component({
selector: 'app-component-overview',
If you want your template to span multiple lines, use backticks (`). For example:
@Component({
selector: 'app-component-overview',
template: `
<h1>Hello World!</h1>
<p>This template definition spans multiple lines.</p>
`
})
o To create an attribute directive, use the Angular CLI command ng generate directive
<directive-name>.
o For instance, if you want to create a directive called “highlight,” run:
ng generate directive highlight
o This generates the directive file (highlight.directive.ts) and a corresponding test file
(highlight.directive.spec.ts).
Let’s create a simple directive that highlights an element by changing its background
color to yellow when the user hovers over it.
Here’s the code for the highlight.directive.ts:
TypeScript
highlight.directive.ts
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter')
onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave')
onMouseLeave() {
this.highlight('');
}
HTML
Todolist.component.html
<div class="container">
<hr>
<div class="form-group">
<label for="task">Task</label>
class="form-text text-danger">Required
field</small>
</div>
btn-primary">Submit</bu on>
</form>
<hr>
<table class="table">
<thead>
<tr>
<th scope="col">Task</th>
<th scope="col">Completed</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<td>{{t.taskName}}</td>
(click)="onDelete(i)">Delete</bu on></td>
</tr>
</tbody>
</table>
</div>
Todolist.component.ts
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.css']
})
constructor() { }
ngOnInit(): void {
onSubmit(form: NgForm) {
console.log(form);
this.taskArray.push({
taskName: form.controls['task'].value,
isCompleted: false
})
form.reset();
onDelete(index: number) {
console.log(index);
this.taskArray.splice(index, 1);
onCheck(index: number) {
console.log(this.taskArray);
this.taskArray[index].isCompleted = !this.taskArray[index].isCompleted;
}
5.Implement routing and navigation in Angular JS
How to implement routing and navigation in an Angular application without using modules.
1.Create an Angular Application: First, create a new Angular project using the following command:
ng new angular-routing-without-modules
2.Create Components: Generate components for different views/pages within your app:
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
4.Create Navigation Links: In your app.component.html, add navigation links to your views
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/contact">Contact</a>
</nav>
<router-outlet></router-outlet>
<h1>About Us</h1>
<h1>Contact Us</h1>
ng serve
Visit http://localhost:4200 in your browser, and you’ll see your navigation links. Clicking on
them will load the corresponding views.
REACT JS
Experiment : 1.React Components
Components:
React components are piece of code which we can use many times at any where in the
project.
There are two types of react components:
1.class components
2.function components
Class components:
Class components are constructed by extending React.Component
Ex:
import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
render()
{
return(<h1>hello world</h1>);
}
}
ReactDOM.render(<Component1 />,document.getElementById('root'));
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoApp from './TodoApp';
ReactDOM.render(
<React.StrictMode>
<TodoApp />
</React.StrictMode>,
document.getElementById('root')
);
'https://api.themoviedb.org/3/search/movie?api_key=fb5be735705694186dd43ba8fe1
9143f&query=The%20Marvels'
);
const data = await response.json();
setMovies(data.results);
} catch (error) {
console.error('Error fetching movies:', error);
}
};
return (
<div>
<h2>Movie List</h2>
<ul>
{movies.map(movie => (
<MovieItem key={movie.id} movie={movie} />
))}
</ul>
</div>
);
};
export default MovieList;
MovieItem.js
import React from 'react';
const MovieItem = ({ movie }) => {
return (
<li>
<img
src={`https://image.tmdb.org/t/p/w200/${movie.poster_path}`}
alt={movie.title}
/>
<h3>{movie.title}</h3>
<p>{movie.release_date}</p>
</li>
);
};
Install additional dependencies: You'll need some additional dependencies for building a
PWA. Install them using npm or yarn:
function Header() {
return (
<header>
<h1>My PWA App</h1>
</header>
);
}
export default Header;
Create your main application: Use these reusable components to build your main
application. Here's an example of how you might structure your main application using React
Router for navigation:
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Header from './Header';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<div>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
</Router>
);
}
export default App;
Define your routes: Create separate components for each route of your application. For
example:
// Home.js
import React from 'react';
function Home() {
return (
<div>
<h2>Welcome to the Home page!</h2>
</div>
);
}
export default Home;
// About.js
import React from 'react';
function About() {
return (
<div>
<h2>About Us</h2>
<p>This is the about page of our application.</p>
</div>
);
}
export default About;
Make your app a PWA: To turn your React app into a PWA, you need to add a manifest file
(manifest.json) and a service worker (service-worker.js). You can use tools like create-react-
app to generate these files automatically, or you can create them manually.
Test your PWA: Once everything is set up, test your PWA in a browser that supports service
workers. You should be able to see your app load even when offline, thanks to the service
worker caching.
Django
Django is a high-level Python framework designed for rapid, secure, and scalable web development. Django
includes rich support for URL routing, page templates, and working with data.
Installation of Django
Create a project environment for the Django Tutorial
In this section, you create a virtual environment in which Django is installed. Using a virtual environment
avoids installing Django into a global Python environment and gives you exact control over the libraries
used in an application. A virtual environment also makes it easy to Create a requirements.txt file for the
environment.
On your file system, create a project folder for this tutorial, such as hello_django.
In that folder, use the following command (as appropriate to your computer) to create a virtual environment
named .venv based on your current interpreter:
# Windows
py -3 -m venv .venv
.venv\scripts\activate
Open the project folder in VS Code by running code ., or by running VS Code and using the File > Open
Folder command.
In VS Code, open the Command Palette (View > Command Palette or (Ctrl+Shift+P)). Then select the
Python: Select Interpreter command:
The command presents a list of available interpreters that VS Code can locate automatically (your list will
vary; if you don't see the desired interpreter, see Configuring Python environments). From the list, select the
virtual environment in your project folder that starts with ./.venv or .\.venv:
Run Terminal: Create New Terminal (Ctrl+Shift+`) from the Command Palette, which creates a terminal and
automatically activates the virtual environment by running its activation script.
The selected environment appears on the right side of the VS Code status bar, and notices the ('.venv': venv)
indicator that tells you that you're using a virtual environment:
Update pip in the virtual environment by running the following command in the VS Code Terminal:
Install Django in the virtual environment by running the following command in the VS Code
Terminal:
python -m pip install Django
This startproject command assumes (by use of . at the end) that the current folder is your project
folder, and creates the following within it:
manage.py: The Django command-line administrative utility for the project. You run administrative
commands for the project using python manage.py <command> [options].
__init__.py: an empty file that tells Python that this folder is a Python package.
asgi.py: an entry point for ASGI-compatible web servers to serve your project. You typically leave
this file as-is as it provides the hooks for production web servers.
settings.py: contains settings for Django project, which you modify in the course of developing a web
app.
urls.py: contains a table of contents for the Django project, which you also modify in the course of
development.
wsgi.py: an entry point for WSGI-compatible web servers to serve your project. You typically leave
this file as-is as it provides the hooks for production web servers.
When you run the server the first time, it creates a default SQLite database in the file db.sqlite3 that is
intended for development purposes, but can be used in production for low-volume web apps.
o verify the Django project, make sure your virtual environment is activated, then start Django's
development server using the command python manage.py runserver. The server runs on the default
port 8000, and you see output like the following output in the terminal window:
Django's built-in web server is intended only for local development purposes. When you deploy to a
web host, however, Django uses the host's web server instead. The wsgi.py and asgi.py modules in the
Django project take care of hooking into the production servers.
If you want to use a different port than the default 8000, specify the port number on the command line,
such as python manage.py runserver 5000.
Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open your default browser
to that address. If Django is installed correctly and the project is valid, you see the default page shown
below. The VS Code terminal output window also shows the server log.
When you're done, close the browser window and stop the server in VS Code using Ctrl+C as
indicated in the terminal output window
Django-admin is used to create Django project. It provide basic initial setup and It configure and
database.
mysite/ manage.py
mysite/
urls.py asgi.py
wsgi.py
We are creating app called polls and we will do all work in polls apps itself
apps.py migrations/
tests.py views.py
Let’s Write first Basic view
Polls/views.py
def index(request):
We had created view right, we also need urls.py file as url routing should be like
some.com/polls/ this search for polls app to urls file to index function.
Polls/urls.py
urlpatterns = [
After creating we need to configure our project urls. Go to mysite folder which will be in mysite folder.
And open urls.py file
mysite/urls.py
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
You will get Hello world….. text from the index function from polls view file And congrats we had
created basic view we can as many views in polls view with same syntax.
class Question(models.Model):
question_text = models.CharField(max_length=200) pub_date
= models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Here, each model is represented by a class that subclasses django.db.models.Model. Each model has
a number of class variables, each of which represents a database field in the model.
Each field is represented by an instance of a Field class – e.g., CharField for character
felds and DateTimeField for datetimes. This tells Django what type of data each field
holds.
To activate we need to first add our polls INSTALLED_APPS which is in the settings.py file in mysite file.
mysite/settings.py INSTALLED_APPS =
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
It will show all changes that are made in the models.py file, We had created new model
Question, Choice so, It shows as Created.
Admin Panel
Creating the Super user
Using this we will be creating super user
This will ask few info make sure Username and Password. Username: Admin, Password: root
while typing password it will appear just type and go.
Now go to http://127.0.0.1:8000/admin it prompt login system
admin.site.register(Question)
we are importing the Question from model and registering it Try the same for Choice just add Choice to
import and register with the same syntax. After saving you will get like this
Q. Writing Django templates for rendering data?
Note:
If they only for ask for template write about creating templates folder and file location
“polls/template/polls/index.html” polls view and view file. For templates we need urls.py, views.py,
template file.
Templates in Django?
We will be creating updating the project to show to questions and showing dynamic content based on
urls
Let’s Fist add few more views to polls/view.py folder.
Data rendering dynamically from view and also write index function which is in below the screenshot
Add this lines this is to the polls/view.py
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
urlpatterns = [
path('', views.index, name='index'),
Here taking number which passing in url as our question id and using it view file.
<int:question_id>
<datatype:variable_name name=”view name”>
Same for <int:question_id/results it will rendering results which question it.
Let’s Update Index view to Show all the data in database
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
return HttpResponse(output)
Add these and replace the index view with this code.
Explanation:
We getting all latest question from using objects which is predefined in models and orderby date
created upto top 5.
Create new questions in Admin panel in case you had not created one
Now let’s create one template.
Django had predefined structure to create templates.
Create template file.
In polls folder create templates (currently we only specific to the polls app only). Create another folder
with name of app name we had polls so we will be create as polls and create new file index.html
polls/template/polls/index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Explanation:
We use {{ }} for variables. We use {% %} for writing tags it used to write more complex than
variables like logic and some conditionals. If latest_question_list is exist it wil return Boolean as true
we already know that if true it executes as printing all the question text
Output will be polls index and Dynamically showing Question_id, results.. Polls/
polls/2
Polls/2/results/
It can work with any number we just getting number from url and showing in the view
Django REST Framework Django REST Framework is added just like any other third-party app. Make sure
to quit the local server Control+c if it is still running. Then on the command line type the below
Add rest_framework to the INSTALLED_APPS config in our settings.py file. I like to make a distinction
between third-party apps and local apps as follows since the number of apps grows quickly in most projects.
# library_project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework', # new
]
Ultimately our API will expose a single endpoint that lists out all books in JSON. So we will need a new
URL route, a new view, and a new serializer file (more on this shortly). There are multiple ways we can
organize these files however my preferred approach is to create a dedicated api app. That way even if we add
more apps in the future, each app can contain the models, views, templates, and urls needed for dedicated
webpages, but all API-specific files for the entire project will live in a dedicated api app. Let’s first create a
new api app.
# library_project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework',
# Local
'api.apps.ApiConfig', # new
]
The api app will not have its own database models so there is no need to create a migration file and update
the database as we normally would.
URLs Let’s start with our URL configs. Adding an API endpoint is just like configuring a traditional Django
app’s routes. First at the project-level we need to include the api app and configure its URL route, which will
be api/.
# library_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns
= [ path('admin/', admin.site.urls), path('', include('books.urls')), path('api/', include('api.urls')), # new ]
Views Next up is our views.py file which relies on Django REST Framework’s built-in generic class views.
These deliberately mimic traditional Django’s generic class-based views in format, but they are not the same
thing. To avoid confusion, some developers will call an API views file apiviews.py or api.py. Personally,
when working within a dedicated api app I do not find it confusing to just call a Django REST Framework
views file views.py but opinion varies on this point. Within our views.py file, update it to look like the
following:
# api/views.py
from rest_framework import generics
from books.models import Book
from .serializers import BookSerializer
class BookAPIView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
Serializers A serializer translates data into a format that is easy to consume over the internet, typically JSON,
and is displayed at an API endpoint. We will also cover serializers and JSON in more depth in following
chapters. For now I want to demonstrate how easy it is to create a serializer with Django REST Framework
to convert Django models to JSON
# api/serializers.py
from rest_framework import serializers
from books.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'subtitle', 'author', 'isbn')
On the top lines we import Django REST Framework’s serializers class and the Book model from our books
app. We extend Django REST Framework’s ModelSerializer into a BookSerializer class that specifies our
database model Book and the database fields we wish to expose: title, subtitle, author, and isbn.
We want to see what our API endpoint looks like. We know it should return JSON at the URL
http://127.0.0.1:8000/api/. Let’s ensure that our local Django server is running:
Now open a new, second command line console. We will use it to access the API running in the existing
command line console. We can use the popular cURL program to execute HTTP requests via the command
line. All we need for a basic GET request it to specify curl and the URL we want to call.
$ curl http://127.0.0.1:8000/api/
[
{
"title":"Django for Beginners",
"subtitle":"Build websites with Python and Django",
"author":"William S. Vincent",
"isbn":"978-198317266"
}
]
The data is all there, in JSON format, but it is poorly formatted and hard to make sense of. Fortunately
Django REST Framework has a further surprise for us: a powerful visual mode for our API endpoints.
Browsable API With the local server still running in the first command line console, navigate to our API
endpoint in the web browser at http://127.0.0.1:8000/api/