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>
Related
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}}
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 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.
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