You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.6 KiB
2.6 KiB
Using an API with AJAX
Lesson Objectives
- Create a new app
- Generate a new component
- Clean up app.component.html
- Add search component to app
- Add Form HTML to search component
- Import Form functionality into the app
- Set a component property to the value of an input
- Invoke a function when the user clicks a button
Create a new app
ng new starwars
cd starwars
ng serve --open
Generate a new component
ng generate component search
Clean up app.component.html
Set src/app/app.component.html contents to:
<h1>Star Wars Character Search App</h1>
Add search component to app
Edit src/app/app.component.html:
<h1>Star Wars Character Search App</h1>
<app-search></app-search>
Add Form HTML to search component
Edit src/app/search/search.component.html:
<section>
<h2>Search For A Star Wars Character</h2>
<input type="text" placeholder="Character Name"/>
<input type="submit" value="Search"/>
</section>
Import Form functionality into the app
Edit src/app/app.module.ts to import FormsModule and place it as an import:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SearchComponent } from './search/search.component';
import { FormsModule } from '@angular/forms'; //import FormsModule
@NgModule({
declarations: [
AppComponent,
SearchComponent
],
imports: [
BrowserModule,
FormsModule //add it as an import
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Set a component property to the value of an input
In src/app/search/search.component.html, add [(ngModel)] to the text input:
<section>
<h2>Search For A Star Wars Character</h2>
Search String: {{name}}
<input [(ngModel)]="name" type="text" placeholder="Character Name"/>
<input type="submit" value="Search"/>
</section>
Test this by changing the text in the input field
Invoke a function when the user clicks a button
In src/app/search/search.component.ts add a findCharacter method to SearchComponent:
findCharacter(name){
console.log('finding ' + name);
}
Call it in src/app/search/search.component.html (also remove the Search String:{{name}} test code):
<section>
<h2>Search For A Star Wars Character</h2>
<input [(ngModel)]="name" type="text" placeholder="Character Name"/>
<input (click)="findCharacter(name)" type="submit" value="Search"/>
</section>
Test this by looking in the console