Getting error while passing event.target.value in angular ts - html

My app.component.html code is :
<h1>Password Generator</h1>
<div>
<label>Length</label>
</div>
<input (input)="onChangeLength($event.target.value)"/>
<div>
<div>
<input (change)="onChangeHandlerLetter()" type="checkbox" />
<label>Use Letter</label>
</div>
<div>
<input (change)="onChangeHandlerNumbers()" type="checkbox" />
<label>Use Numbers</label>
</div>
<div>
<input (change)="onChangeHandlerSymbols()" type="checkbox" />
<label>Use Symbols</label>
</div>
<div>
<button (click)="onButtonClick()">Generate</button>
</div>
</div>
<div>
<label>Your Password</label>
</div>
<input [value]="password"/>
{{password}}
My app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
length=0;
includeLetters=false;
includeSymbols=false;
includeNumbers=false
onChangeHandlerLetter=()=>{
this.includeLetters=!this.includeLetters
}
onChangeHandlerSymbols=()=>{
this.includeSymbols=!this.includeSymbols
}
onChangeHandlerNumbers=()=>{
this.includeNumbers=!this.includeNumbers
}
onChangeLength=(val:string)=>{
const parsedValue=parseInt(val);
if(!isNaN(parsedValue)){
this.length=parsedValue
}
console.log(length);
}
password=" "
onButtonClick=()=>{
this.password="My Password"
console.log("button clicked");
console.log(`Following should be included :
Sybmols : ${this.includeSymbols}
Numbers : ${this.includeNumbers}
Letters : ${this.includeLetters}`)
}
}
error :
index.js:561 [webpack-dev-server] ERROR
src/app/app.component.html:5:46 - error TS2531: Object is possibly 'null'.
5 <input (input)="onChangeLength($event.target.value)"/>
~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
Hello greetings community , I am new to TS and angular so I dont know why I am getting this error I need to take input from input bar and change into number and console.log I am following a tutorial and he is getting correct output I dont know why

You need to tell TypeScript the type of the HTMLElement which is your target.
To do so instead of $event.target.value please use $event as below:
<input (input)="onChangeLength($event)"/>
then in app.component.ts use:
const parsedValue=parseInt((<HTMLInputElement>event.target).value);
Working codes:
app.component.ts
import { Component } from '#angular/core';
import { ColdObservable } from 'rxjs/internal/testing/ColdObservable';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
length=0;
includeLetters=false;
includeSymbols=false;
includeNumbers=false
onChangeHandlerLetter=()=>{
this.includeLetters=!this.includeLetters
}
onChangeHandlerSymbols=()=>{
this.includeSymbols=!this.includeSymbols
}
onChangeHandlerNumbers=()=>{
this.includeNumbers=!this.includeNumbers
}
onChangeLength=( event: Event)=>{
const parsedValue=parseInt((<HTMLInputElement>event.target).value);
if(!isNaN(parsedValue)){
this.length=parsedValue
}
console.log(length);
}
password=" "
onButtonClick=()=>{
this.password="My Password"
console.log("button clicked");
console.log(`Following should be included :
Sybmols : ${this.includeSymbols}
Numbers : ${this.includeNumbers}
Letters : ${this.includeLetters}`)
}
}
app.component.html
<h1>Password Generator</h1>
<div>
<label>Length</label>
</div>
<input (input)="onChangeLength($event)"/>
<div>
<div>
<input (change)="onChangeHandlerLetter()" type="checkbox" />
<label>Use Letter</label>
</div>
<div>
<input (change)="onChangeHandlerNumbers()" type="checkbox" />
<label>Use Numbers</label>
</div>
<div>
<input (change)="onChangeHandlerSymbols()" type="checkbox" />
<label>Use Symbols</label>
</div>
<div>
<button (click)="onButtonClick()">Generate</button>
</div>
</div>
<div>
<label>Your Password</label>
</div>
<input [value]="password"/>
{{password}}

Related

how to use checkbox in reactive angular form

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

The Validators And Errors Are Not Working In Angular 9

I have started working on Angular 9 and I am using the Reactive Form in Angular 9 but the problem is that the validators and errors are not working for the form.
This is my app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This is my app.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '#angular/forms';
import { MustMatch } from './_helpers/must-match.validator';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'my-assignment';
submitted = false;
show: boolean;
profileForm: FormGroup;
constructor(private fb: FormBuilder) {
this.show = true;
}
ngOnInit() {
this.profileForm = this.fb.group({
email: ['', [Validators.required, Validators.pattern('[a-z0-9.#]*')]],
password: ['', [Validators.required, Validators.minLength(8)]],
confirmpassword: ['', Validators.required],
}, {
validator: MustMatch('password', 'confirmpassword')
});
}
get f() { return this.profileForm.controls; }
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.profileForm.value);
}
// click event function toggle
password() {
this.show = !this.show;
}
}
This is my app.component.html:
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<form style="margin-top: 100px;" [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="firstName">Email: </label>
<input type="text" placeholder="Email" formControlName="email">
<div *ngIf="f.email.hasError('pattern')">
Oops, wrong pattern buddy!
</div>
</div>
<div class="form-group">
<label for="password">Password: </label>
<input [type]="show ? 'text' : 'password'" placeholder="Password" formControlName="password">
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div class="form-group">
<label for="confirmpassword">Confirm Password: </label>
<input type="password" placeholder="Confirm Password" formControlName="confirmpassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />
<div *ngIf="submitted && f.confirmpassword.errors" class="invalid-feedback">
<div *ngIf="f.confirmpassword.errors.required">Confirm Password is required</div>
<div *ngIf="f.confirmpassword.errors.mustMatch">Passwords must match</div>
</div>
</div>
<button (click)="password()">Show Password</button>
<button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>
</div>
</div>
</div>
</div>
This is my must-match.validator.ts:
import { FormGroup } from '#angular/forms';
// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
};
}
core.js:6185 ERROR TypeError: Cannot read property 'errors' of undefined
Any help is much appreciated.
You have a typo : confirmPassword ( *ngIf="f.confirmPassword.errors.required").
It's confirmpassword everywhere else.

How to display form data in popup after clicking on submit button

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

my 'ngSubmit' sometimes error

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

Angular data ist not defined

simple question, I try to implement a login form and store it into the variable "data". But the console tells me ERROR ReferenceError: data is not defined.
But I did defined it. What did I do wrong?
Loginform.component.ts:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-loginform',
templateUrl: './loginform.component.html',
styleUrls: ['./loginform.component.css']
})
export class LoginformComponent implements OnInit {
data = {};
constructor(private router:Router, private user:UserService) { }
ngOnInit() {
}
formSubmit() {
if(data.username == 'admin' && data.passwd == 'test'){
user.setUserLoggedIn();
this.router.navigate(['dashboard']);
}
};
}
loginform.component.html:
<div class="loginFlexCenter">
<div class="loginForm">
<h2> Studienverlaufsplan Login </h2>
<hr>
<form class="inputDiv" (ngSubmit)="formSubmit()">
<div class="inputDiv">
<label>Username:</label>
<input class="txtInput" type="text" name="username" [(ngModel)]="data.username"><br/>
</div>
<div class="inputDiv">
<label>Password:</label>
<input class="txtInput" type="password" name="password" [(ngModel)]="data.passwd">
</div>
<div class="inputDivHalf">
<input class="txtInput" type="submit" value="Submit"/>
<input routerLink="/register" routerLinkActive="active" class="txtInput" type="submit" value="Register"/>
</div>
</form>
</div>
</div>