I am new to Angular 2 and Typescript but I am trying to build a web app.
I build some input fields and I want to log them to the console after submitting them via a button. But my button does not really work or react.
Does anyone have an idea what is the problem with my code?
Here is my code:
app.component.html
<div class="panel panel-primary">
<div class="panel-heading">Status</div>
<div class="panel-body">
<h3>{{title}}</h3>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<div class="form-group">
<label>Street</label>
<input type="text" class="form-control" name="street" ngModel>
</div>
<div class="form-group">
<label>PLZ</label>
<input type="text" class="form-control" name="plz" ngModel>
</div>
</form>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
app.component.ts
import { Component, style } from '#angular/core';
import { TutorialsComponent } from './tutorial.component';
import { SteliosComponent } from './stelios.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public title ="Das ist die erste Componente"
public childData: string;
onSubmit(value: any){
console.log(value);
}
}
Your button isn't in your form. Put it in your form and you're good to go !
You have to associate the submit button with the form.
This is usually done by putting the <button> element inside the <form> element.
You could do that by moving it to just before </form>.
Alternatively, you could use the form attribute:
<button form="id_of_form_element_goes_here" type="submit" class="btn btn-primary">Submit</button>
… but browser support for that is weaker.
Move the submit button inside the form.
<form>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Related
There is a form on angular 8
my-form.component.html
<div class="container">
<form novalidate [formGroup]="registrationForm">
<div class="form-group">
<label for="firstName">Имя:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="firstName" id="firstName" type="text" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName">Фамилия:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="lastName" id="lastName" type="text" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<label for="email">E-mail:</label>
<input #spy required email name="email" id="email" type="email" class="form-control" formControlName="email">
</div>
<!--{{ spy.className }}-->
<button type="submit" class="btn btn-succes" (click)="submit(myForm)">Отправить</button>
</form>
When the user writes data, the submit button should send data to the API using the POST method.
If you need any code, leave a comment
ts code:
import { FormGroup, FormControl } from '#angular/forms';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
registrationForm: FormGroup;
constructor() { }
ngOnInit() {
this.registrationForm = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
email: new FormControl()
});
}
}```
i have simple example for you....
reference
----html----
<header class="masthead">
<div class="container h-100">
<div class="row h-100 align-items-center justify-content-center">
<div class="col-6">
<div class="text-center">
<hello name="{{ name }}"></hello>
<hr>
</div>
<form #send="ngForm" (ngSubmit)="sendFRMData(send.value)">
<div class="form-group">
<label for="title" class="text-muted">Title</label>
<input type="text" class="form-control" id="title"
name="titlefrm" ngModel #title='ngModel' required>
<span class="help-block text-danger" *ngIf="!title.valid &&
title.touched">Please give Title!!</span>
</div>
<div class="form-group">
<label for="body" class="text-muted">Body</label>
<input type="text" class="form-control" id="body" name="bodyfrm" ngModel
#body='ngModel' required>
<span class="help-block text-danger" *ngIf="!body.valid &&
body.touched">Please
give Body!!</span>
</div>
<div class="form-group">
<label for="userId" class="text-muted">UserID</label>
<input type="text" class="form-control" id="userId" name="userIdfrm" ngModel
#userid='ngModel' required>
<span class="help-block text-danger" *ngIf="!userid.valid &&
userid.touched">Please give UserID!!</span>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control btn btn-success" type="submit"
[disabled]='!send.valid'>
</div>
<div class="col-sm-6">
<input class="form-control btn btn-info" type="button" value="EDIT"
(click) = 'onEdit()'>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
----ts----
import { NgForm } from '#angular/forms';
#ViewChild('send') send: NgForm;
constructor(private sendData: HttpService) {
}
sendFRMData(data: any) {
const payload = {
title: data.titlefrm,
body: data.bodyfrm,
userId: data.userIdfrm
}
this.sendData.try(payload).subscribe(
(data: any) => {
this.respondedData = JSON.stringify(data);
this.alert = true;
}
);
}
----service----
try(data){
return
this.http.post('https://jsonplaceholder.typicode.com/posts',data,{
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
}
hope you get your answer...
Seems like you are not able to get form values in your submit function.
change your click event from (click)="submit(myForm)" to (click)="submit(myForm.value)" then in your submit function you can call post method
submit(formValueObject) {
console.log(formValueObject);
this.httpService.post(url, formValueObject).subscribe((res:any)=> {
//your response
})
}
I hope it helps
Well, this is the component where I'm trying to create all the content. It is a crud that saves the data when and what I want is for the modal to disappear.
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2>Codigos De <b>Acceso.</b></h2>
</div>
<div class="col-sm-6">
<i class="material-icons"></i> <span>Agregar nuevo codigo</span>
</div>
</div>
</div>
<div class='col-sm-12 pull-right d-flex flex-row-reverse'>
<div id="custom-search-input">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar" aria-label="Input group example" aria-describedby="btnGroupAddon2">
<div class="input-group-append">
<button class="btn btn-primary" id="btnGroupAddon2"><i class="fas fa-search"></i></button>
</div>
</div>
</div>
</div>
<div class='clearfix'></div>
<hr>
<div id="loader"></div>
<div id="resultados"></div>
<div class='outer_div'></div>
</div>
</div>
<!-- Add Modal HTML -->
<div id="addProductModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form #dataForm="ngForm" (ngSubmit)="addData(dataForm)">
<div class="modal-header">
<h4 class="modal-title">Añadir Codigo</h4>
<button type="button" class="close" data-dismiss="modal" id="dismiss" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Código</label>
<input type="text" name="code" class="form-control" #code="ngModel" [(ngModel)]="dataService.selectedData.code" required >
</div>
<div class="form-group">
<label>Dirección</label>
<input type="text" name="direction" class="form-control" #direction="ngModel" [(ngModel)]="dataService.selectedData.direction" required>
</div>
<div class="form-group">
<label>Comentario</label>
<input type="text" name="comment" class="form-control" #comment="ngModel" [(ngModel)]="dataService.selectedData.comment" required>
</div>
<div class="form-group">
<label>Tech #</label>
<input type="number" name="tech" class="form-control" #tech="ngModel" [(ngModel)]="dataService.selectedData.tech" required>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-secondary" data-dismiss="modal" value="Cancelar">
<input type="submit" class="btn btn-primary" value="Guardar datos">
</div>
</form>
</div>
</div>
</div>
<div class="center">
and this is my ts file:
import { Component, OnInit } from '#angular/core';
import { Data } from '../../models/data' // La ruta puede ser distinta.
import { DataService } from '../../services/data.service';
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-datas',
templateUrl: './datas.component.html',
styleUrls: ['./datas.component.css'],
providers: [DataService]
})
export class DatasComponent implements OnInit {
constructor(private dataService: DataService) { }
ngOnInit() {}
addData(form: NgForm) {
this.dataService.postData(form.value)
.subscribe(res => {
this.resetForm(form);
})
}
/*
close(form?: NgForm){
if
}*/
resetForm(form?: NgForm) {
if(form){
form.reset();
var dismiss = document.querySelector('#addProductModal');
console.log(dismiss);
this.dataService.selectedData = new Data();
}
}
}
As you can see, that last method is called resetForm, I tried to clean the form when the data is sent and I have achieved it, but what I need is that the modal is discarded. Anyone have an idea?
NPM uninstall jQuery right away. Don't use the JavaScript version of bootstrap, install ngx-bootstrap and use the Angular components. They play much nicer with Angular. Your component should not be inspecting the DOM with querySelector and you shouldn't use any jQuery. If you rewrite the component using ngx-bootstrap you will be able to get an instance of an Angular modal component and call close.
https://valor-software.com/ngx-bootstrap/#/modals
I am trying to change inner HTML content of a div by id with another div in angular component method. I am able to call populateEndpointHomeContent() and get that content but not further content. Actually those methods populateAddEndpoint() and populateAddEndpointForm are not getting called on click. I am not getting any console error also. Any idea how I can get this?
endpoint.component.html
<div id="endpoint_home"></div>
<div id="endpoint_home_content" style="display:none">
<button class="btn btn-sm" (click)="populateAddEndpoint();">+ Add Endpoint</button>
</div>
<!-- Add Endpoint DIVS Starts -->
<div id="add_endpoint_home" style="display:none">
<form #endpointForm="ngForm">
<section class="form-block">
<div class="form-group">
<label for="endPointType">Select Endpoint Type</label>
<div class="select">
<select id="endPointType" (change)="populateAddEndpointForm(this.value);">
<option>MACHINE</option>
<option>K8S_CLUSTER</option>
<option>AWS</option>
<option>DOCKER</option>
<option>VCENTER</option>
<option>WAVEFRONT</option>
<option>VRNI</option>
</select>
</div>
</div>
<div id="add_endpoint_form"></div>
<button type="submit" class="btn btn-primary">ADD</button>
</section>
</form>
</div>
<div id="add_machine_form" style="display:none">
<div class="form-group">
<label for="name">Endpoint Name</label>
<input type="text" placeholder="Endpoint Name" size="42" id="name" name="name" [(ngModel)]="name" required>
</div>
<div class="form-group">
<label for="credentialsName">Credential Name</label>
<div class="select">
<select id="credentialsName">
<option>MACHINE</option>
</select>
</div>
</div>
<button type="button" class="btn btn-primary">ADD CREDENTIAL</button>
<div class="form-group">
<label for="host">Machine Host/IP</label>
<input type="text" placeholder="0.0.0.0" size="42" id="host" name="host" [(ngModel)]="host" required>
</div>
<div class="form-group">
<label for="sshPort">SSH Port</label>
<input type="number" placeholder="22" size="42" id="sshPort" name="sshPort" [(ngModel)]="sshPort" required>
</div>
<div class="form-group">
<label for="timeout">SSH Timeout</label>
<input type="number" placeholder="60" size="42" id="timeout" name="timeout" [(ngModel)]="timeout" required>
</div>
<div class="form-group">
<label for="osType">OS Type</label>
<div class="select">
<select id="osType">
<option>WINDOWS</option>
<option>LINUX</option>
</select>
</div>
</div>
</div>
<!-- Add Endpoint DIVS Ends -->
EndpointComponent
import { Component, OnInit } from '#angular/core';
import { EndpointService } from './endpoint.service';
#Component({
selector: 'app-endpoint',
templateUrl: './endpoint.component.html',
styleUrls: ['./endpoint.component.scss']
})
export class EndpointComponent implements OnInit {
constructor(private endpointService: EndpointService) { }
public wavefrontendpoints: any;
ngOnInit() {
this.populateEndpointHomeContent();
this.endpointService.getAllEndpoints().subscribe(res => this.wavefrontendpoints = res.response[0]);
}
public populateEndpointHomeContent() {
document.getElementById('endpoint_home').innerHTML = document.getElementById('endpoint_home_content').innerHTML;
}
public populateAddEndpoint() {
console.log('Inside populateAddEndpoint...');
document.getElementById('endpoint_home').innerHTML = document.getElementById('add_endpoint_home').innerHTML;
}
public populateAddEndpointForm(endPointType) {
console.log('Inside populateAddEndpointForm...');
if(endPointType === 'MACHINE') { document.getElementById('add_endpoint_form').innerHTML = document.getElementById('add_machine_form').innerHTML; }
}
}
Trying to render HTML content from its innerHTML will not have its prototype functions work.
Your HTML will be visible, but it won't make their click events trigger, because innerHTML only contains the HTML markup, not the function or event prototypes.
Go through Angular's Guide on Dynamic Component Loader, which is about loading dynamic content in an HTML page.
I want to write a function with get two values from two inputs and calculate something like BMI (Body Mass Index).
My HTML file:
<div class="input-group mb-3 weight-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Weight</span>
</div>
<input ng-model="weight" type="text" class="form-control" placeholder="[kg]" aria-label="Waga[kg]" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3 growth-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Growth</span>
</div>
<input ng-model="growth" type="text" class="form-control" placeholder="[m]" aria-label="Wzrost[m]" aria-describedby="basic-addon1">
</div>
<button (click)="calculate()" type="button" class="btn btn-primary btn-sm ml-3">Large button</button>
<div class="alert alert-dark" id="result" role="alert">
</div>
My TS file:
import { Component, OnInit } from '#angular/core';
import { NgModel } from '#angular/forms';
#Component({
selector: 'app-inputs',
templateUrl: './inputs.component.html',
styleUrls: ['./inputs.component.css'],
})
export class InputsComponent implements OnInit {
constructor() { }
ngOnInit() {
}
calculate() {
}
}
What should I write in function calculate () to see get values from weight and growth inputs and how can I export for example value from variable bmi to div id="result" ?
Thanks for help!
Take advantage of Angular's two way data binding with [(ngModel)]. This way you do not even need the calculate function, and can get the calculation preview in real time.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template:`
<input [(ngModel)]="mass" placeholder="mass" />
<input [(ngModel)]="height" placeholder="height" />
<div *ngIf="mass && height"> {{ bmi }} </div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
mass = 0;
height = 0;
get bmi() {
return this.mass / Math.pow(this.height, 2);
}
}
Live demo
Use two way data binding on your weight and growth properties and simply pass them as argument to your calculate function.
<div class="input-group mb-3 weight-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Weight</span>
</div>
<input [(ngModel)]="weight" type="text" class="form-control" placeholder="[kg]" aria-label="Waga[kg]" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3 growth-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Growth</span>
</div>
<input [(ngModel)]="growth" type="text" class="form-control" placeholder="[m]" aria-label="Wzrost[m]" aria-describedby="basic-addon1">
</div>
<button (click)="calculate(weight, growth)" type="button" class="btn btn-primary btn-sm ml-3">Large button</button>
<div class="alert alert-dark" id="result" role="alert">
</div>
and:
calculate(weight, growth) {
console.log(weight, growth)
}
Demo
Then modify your calculate function to actually do something useful.
im trying to get some values in forms using the submit event. But i can´t reset those forms later. Im trying to use an id called "myForm" and an onclick function
<form (Submit)="addMarker()" id="myForm">
<div class="row">
<div class="col">
<input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
</div>
<div class="col">
<input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
</div>
<div class="col-3">
<button type="submit" class="btn btn-primary" onclick="myFunction()">Agregar Marcador</button>
</div>
</div>
</form>
Script:
function myFunction() {
document.getElementById("myForm").reset();
}
In your HTML:
<form (submit)="addMarker(myForm)" id="myForm" #myForm="ngForm"> // <-- Notice the "#"
<div class="row">
<div class="col">
<input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
</div>
<div class="col">
<input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
</div>
<div class="col-3">
<button type="submit" class="btn btn-primary">Agregar Marcador</button>
</div>
</div>
</form>
In your ts:
Import NgForm first by adding:
import { NgForm } from '#angular/forms';
Function to reset the form:
addMarker(form: NgForm) {
//do something and then reset the form
form.resetForm();
}
For Angular 2 Final, we now have a new API that cleanly resets the form:
#Component({...})
class App {
form: FormGroup;
...
reset() {
this.form.reset();
}
}
This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.