I'm working on REST API, I have one app beck-end in Java 1.6 and another front-end in Angular 4. I want to get the value by id of the HTML tag,
I tried use DOM like this: <HTMLInputElement>document.getElementById(this.keyList[i].keyId)).value; but the problem is I can't use this sintax "this.keyList[i].keyId" because in class Key I have only one constructer, that fetch the attributes in JSON, so, when I go do key.keyId, said it does not exist. Does it exist another away to solve this problem, with propertys of ng? Thanks people.
HTML Code:
<!-- Breadcrumbs -->
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li routerLinkActive="active"><a routerLink="/">Início</a></li>
<li>Consulta</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-12">
<fieldset>
<legend>Consultar Dados Telemáticos</legend>
<form>
<!-- PROVIDERS -->
<div class="row">
<div class="col-md-4">
<label>Provedor</label> <span class="required">*</span>
<br>
<select class="form-control
(ngModel)]="selectedProvider"
(change)="getKey(selectedProvider)" name="provider">
<option *ngFor="let providers of providerHeaderList"
[ngValue]="providers">{{providers.description}}
</option>
</select>
</div>
</div>
<!-- KEYS DYNAMIC -->
<br />
<div class="row">
<div class="col-md-4" *ngFor="let keys of keyList">
<label>{{keys.description}}</label>
<span class="required">*</span>
<input [id]="keys.keyId" class="form-control"
type="text" />
</div>
</div>
<!-- DATE PICK -->
<br />
<div class="row" *ngIf="!keyList?.length==0">
<div class="col-md-4">
<label>Data de Início da Pesquisa</label>
<input class="form-control" type="date"
placeholder="dd/mm/aaaa" data-original-title title />
</div>
</div>
<!-- BUTTON SEARCH -->
<br />
<br />
<div class="row" *ngIf="!keyList?.length==0">
<div class="col-md-4">
<button class="btn btn-primary btn-sm ng-binding"
(click)="btnSearchClick()">Pesquisar</button>
</div>
<div class="col-md-12">
<span><small>* Campos de preenchimento obrigatório.
</small></span>
</div>
</div>
</form>
</fieldset>
</div>
</div>
<!-- RESULTS TABLE -->
<app-provider-result></app-provider-result>
TypeScript Code:
// Angular
import { Component, OnInit, ElementRef } from '#angular/core';
// Serviços
import { ProviderService } from '../../services/provider.service';
import { KeyService } from '../../services/key.service';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
// Modelos
import { Provider } from '../provider';
import { Key } from '../../key/key';
#Component( {
selector: 'app-provider-search',
templateUrl: './provider-search.component.html',
styleUrls: ['./provider-search.component.css']
} )
export class ProviderSearchComponent implements OnInit {
providerHeaderList: Provider[] = [];
keyList: Key[] = [];
selectedProvider = null;
keyValues: string[] = [];
constructor( private providerService: ProviderService, private keyService: KeyService, private myElement: ElementRef ) { }
ngOnInit() {
this.getProviders();
}
getProviders() {
this.providerService.getAllHeaders().subscribe( p => {
this.providerHeaderList = p;
} )
}
getKey(selectedProvider){
this.keyService.getAllKeyByProviderId(selectedProvider.id, selectedProvider.description).subscribe( k => {
this.keyList = k;
});
}
btnSearchClick(){
}
}
You can make use of template refernce
Like
<input type = "text" value = "demo" #ref>
<button (click) = "submit(ref.value)">submit</button>
Now in ts you can use like
ref.value // template val
submit(value){ console.log("Reference value" + value) }
Related
I am new to angular, currently I am looking checkboxes in angular , I have three checkboxes and I have to show checked or unchecked checkboxes in UI.
I am getting enabled/disabled from json , I need to show if am getting enabled means checkbox should be checked and disabled means unchecked checkbox.
This is what am trying in html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label for="email"><input type="checkbox" (change)="onChecked($event)" formcontrolName="emailData" value="{{emailData}}" [checked]="isChecked" >
<b>Email(POP3, IMAP, SMTP)</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label for="ftp"><input type="checkbox" formcontrolName="ftpData" [checked]="isChecked" value="{{ftpData}}"> <b>FTP</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label for="http"><input type="checkbox" formcontrolName="httpData"
[checked]="isChecked"> <b>HTTP</b></label>
</div>
</div>
</form>
typescript file
portFilterForm(){
this.portFilterGroup = this.fb.group({
emailData: new FormControl(''),
ftpData: new FormControl(''),
httpData: new FormControl('')
})
}
onChecked(e){
console.log("e", e.target)
if (e.target == 'enabled'){
this.isChecked = true;
}
else{
this.isChecked = false;
}
}
gettingData(){
this.httpClient.get("assets/json/data.json").subscribe((data:any) =>{
console.log(data);
this.emailData = this.onChecked(data.email)
this.httpData = this.onChecked(data.http)
})
}
and the json file be
{
"email": "enabled",
"ftp": "disabled",
"http": "enabled"
}
this is the code am trying, but am not get the expecting output(enabled means checked and disabled means unchecked) can anyone help me to this?
Ok so you can use the angular way read here
html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['emailData']"
/> <b>Email(POP3, IMAP, SMTP)</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>FTP</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>HTTP</b></label
>
</div>
</div>
</form>
{{ portFilterGroup.value | json }}
<button (click)="gettingData()">submit</button>
ts file
import { Component } from '#angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular 6';
portFilterGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.portFilterForm();
}
portFilterForm() {
this.portFilterGroup = this.fb.group({
emailData: new FormControl(false),
ftpData: new FormControl(false),
httpData: new FormControl(false),
});
}
gettingData() {
console.log(this.portFilterGroup.value);
// this.httpClient.get('assets/json/data.json').subscribe((data: any) => {
// console.log(data);
// this.emailData = this.onChecked(data.email);
// this.httpData = this.onChecked(data.http);
// });
}
}
stackblitz
I have this problem:
Property 'institutionName' does not exist on type 'FormGroup'.
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
My ts code
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, AbstractControl, FormGroup, FormControl, FormArray} from '#angular/forms'
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.scss']
})
export class FormsComponent implements OnInit {
frmValues: object = {};
frmStepper: FormGroup;
public get formArray(): AbstractControl {
// console.log(this.frmStepper.get('steps'));
return this.frmStepper.get('steps');
}
public get frmStepperControl(){
console.log(this.frmStepper.get('steps')['controls'].controls.institutionName);
return this.frmStepper.get('steps')['controls'];
}
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.frmStepper = this.fb.group({
steps: this.fb.array([
this.fb.group({
ieCode: [''],
institutionName: ['', Validators.compose([Validators.required])],
}),
this.fb.group({
telephone1: [null],
}),
])
});
}
submit(): void {
console.log(this.frmStepper.value.steps[0].institutionName);
//this.frmValues = this.frmStepper.value;
}
}
My html code where I'm trying access the touched and errors properties from my institutionName property
<form [formGroup]="frmStepper" (ngSubmit)="submit()">
<timeline-stepper #cdkStepper formArrayName="steps" [linear]="true">
<cdk-step [editable]="false" formGroupName="0" [stepControl]="formArray.get([0])" class="form-cdk">
<div class="row">
<p>Instituição de ensino</p>
<div class="horizontal-divider"></div>
<div class="form-group col-md-6">
<label for="ieCode">Código da IE/IF</label>
<input formControlName="ieCode" type="text" class="form-control" id="ieCode" placeholder="Escreva aqui...">
</div>
<div class="form-group col-md-6">
<label for="institutionName">Nome da Instituição*</label>
<input formControlName="institutionName" type="text" class="form-control" id="institutionName"
placeholder="Escreva aqui..."
required>
<span class="text-danger"
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
Nome da Instituição é obrigatória
</span>
</div>
</div>
<footer class="row">
<div class="col-md-6"></div>
<div class="form-group col-md-3">
<button type="button" class="btn btn-primary next" cdkStepperNext>PRÓXIMO</button>
</div>
</footer>
</cdk-step>
<cdk-step #contacts [editable]="false" formGroupName="1" [stepControl]="formArray.get([1])">
<div class="row">
<div class="form-group col-md-6">
<label for="telephone1">Telef.1</label>
<input formControlName="telephone1" type="number" class="form-control" id="telephone1" placeholder="Escreva aqui.">
</div>
</div>
<footer class="row lastRow">
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary next">PRÓXIMO</button>
</div>
</footer>
</cdk-step>
</timeline-stepper>
</form>
Property 'institutionName' does not exist on type 'FormGroup'.
I'm facing this problem.
In you HTML you have frmStepper.InstitutionName.errors
Should be frmStepperControl.InstitutionName.errors
I am doing project in angular6. I have created registration form. After clicking on button, I need to display those form values in a popup with submit button and after clicking on submit button, form should be submit. I am getting those form values on console, but not getting how to display those form values in popup. Any help please.
registration.html
<nav class="navbar navbar-expand-lg">Header
</nav>
<div class="container">
<form [formGroup]="addForm" (ngSubmit)="onSubmit(addForm.value)" (onclick)="openPopup()">
<h2 class="text-center mt-3">Registration Form</h2>
<div class="card-header mt-3 mb-3">Student Registration</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="usn"><strong>USN</strong></label>
<input type="usn" formControlName="usn" placeholder="usn" name="usn" class="form-control" id="usn">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="firstName"><strong>First Name</strong></label>
<input type="firstName" formControlName="firstName" placeholder="FirstName" name="firstName" class="form-control" id="firstName" ngModel>
</div>
</div>
</div>
<button class="btn btn-success mx-auto d-block">Submit</button>
</form>
</div>
<div class="card-footer">
footer
</div>
registration.ts
import { Component, OnInit } from '#angular/core';
import {FormBuilder, FormGroup, Validators} from "#angular/forms";
#Component({
selector: 'app-student-parent-registration',
templateUrl: './student-parent-registration.component.html',
styleUrls: ['./student-parent-registration.component.css']
})
export class StudentParentRegistrationComponent implements OnInit {
constructor(private formBuilder: FormBuilder) { }
addForm: FormGroup;
ngOnInit() {
console.log("ngOnInit called")
this.addForm = this.formBuilder.group({
usn:[''],
firstName:['']
})
}
onSubmit(data) {
console.log(data);
}
}
}
If you have followed the React approach then you can get form data by the below code
this.packageEditForm.controls["formControlName"].value
so I have this html code.. i tried using (click) function, and its still like this
<div class="container">
<h1><a [routerLink]="['/databuku']"><img src="images/images.png" width="42" height="42"></a>
Add New Book</h1>
<div class="row">
<div class="col-md-6">
<form (ngSubmit)="saveBuku()" #bukuForm="ngForm">
<div class="form-group">
Judul
<input type="text" class="form-control" [(ngModel)]="buku.judul" name="judul" required>
</div>
<div class="form-group">
Author
<input type="text" class="form-control" [(ngModel)]="buku.author" name="author" required>
</div>
<div class="form-group">
Description
<textarea class="form-control" [(ngModel)]="buku.description" name="description" required cols="40" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" [disabled]="!bukuForm.form.valid">Save</button>
</div>
</form>
</div>
</div>
</div>
here is my ts file
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-tambah-buku',
templateUrl: './tambah-buku.component.html',
styleUrls: ['./tambah-buku.component.css']
})
export class ComponentTambahBuku implements OnInit {
buku = {};
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
}
saveBuku() {
this.http.post('http://localhost:8080/buku', this.buku)
.subscribe(res => {
let id = res['id'];
this.router.navigate(['/detail-buku/', id]);
}, (err) => {
console.log(err);
}
);
}
}
no errors found when I open localhost:4200, its just when i press the save button, its like the button doesn't working, not saving and not going to 'detail-buku' page
I want to be able to trigger an on change when a file is selected from a input(file). I want the triggered event to set a textbox to be the name of the file.
I am using HTML5, Typescript and Angular2. I can't figure out or find an example of exactly how to produce the behavior I am after.
see my code below:
component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { Headers, RequestOptions } from '#angular/http';
#Component({
selector: 'testConnection',
// ignore error on require
template: require('./testConnection.component.html')
})
export class TestConnectionComponent {
public http: Http;
public requestData: RequestData;
public constructor(http: Http) {
this.http = http;
(<HTMLInputElement>document.getElementById('fileInput')).onchange = (ev: Event) => {
var fileInput = (<HTMLInputElement>ev.srcElement).files[0];
var fileTextbox = (<HTMLInputElement>document.getElementById('fileTextbox'));
fileTextbox.value = fileInput.name;
}
}
public testButtonClick() {
// Iniatialise Request object
let request: RequestData;
request = { "CountryCode": "", "SiteIDList": "" };
// Get site(s)
var siteIdList = (<HTMLInputElement>document.getElementById('siteIDInput')).value;
// Get selected country
var countryCode = (<HTMLInputElement>document.getElementById('countryDropdown')).value;
// Veryify contents is just site ids.
// TODO
request.CountryCode = countryCode;
request.SiteIDList = siteIdList;
// Set Http POST options
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
// Call Api with test connection data
this.http
.post('/api/TestConnection/TestConnection', JSON.stringify(request), options)
.subscribe(data => {
// alert request ok
alert('ok');
}, error => {
// Log error
console.log(error.json());
});
}
}
interface RequestData {
SiteIDList: string;
CountryCode: string;
}
component.html
<h2>Test Site Connection</h2>
<p>This will allow you to check the connectivity of a set of sites by either individually or uploading a CSV file of Site IDs.</p>
<br />
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Manual Test</h3>
</div>
<div class="panel-body">
<p>
Select the country and the sites you want to test.
</p>
<ul>
<li>Multiple sites can be selected using commas (,).</li>
<li>you can see results in the Site Connection Results tab</li>
</ul>
<br />
<!--Replace with lookup to enabled countries-->
<div class="form-group col-lg-4">
<div class="col-lg-6">
<select class="form-control" id="countryDropdown">
<option>Select Country</option>
<option>US</option>
<option>SG</option>
<option>NL</option>
</select>
</div>
</div>
<div>
<div class="col-lg-4">
<input type="text" class="form-control" placeholder="SiteID(s)" id="siteIDInput" />
</div>
<button class="btn btn-primary" (click)="testButtonClick()">Test</button>
</div>
</div>
</div>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Upload file</h3>
</div>
<div class="panel-body">
<div>
<p>Upload a CSV file of sites to test all at once.</p>
<br />
<div class="col-lg-4">
<input type="text" class="col-lg-4 form-control" id="fileTextbox" disabled/>
</div>
<label class="btn btn-primary">
Browse <input type="file" id="fileInput" style="display:none;" onchange="{ setFileName() }"/>
</label>
<button class="btn btn-primary" (click)="searchButtonClick()">Test</button>
</div>
</div>
</div>
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try using (change) event binding
<input type="file" id="fileInput" style="display:none;" (change)="setFileName()"/>
If you need to retrieve the file name before uploading it you can do it this way :
#Component({
selector: 'my-app',
template: `
<div>
<input type="file" (change)="onChange($event)"/>
</div>
<p>Filename : {{filename}}</p>
`,
providers: []
})
export class AppComponent {
filename: string;
constructor() { }
onChange(event) {
this.filename = event.srcElement.files[0].name;
}
}
Here is a working plunker