Cannot print to console - javascript

I am new to angular and trying to implement a reactive form. Below is my html code and TS code
<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="email">Mail</label>
<input type="email" name="email" id="email" formControlName="email" class="form-control">
</div>
<div class="btn btn-primary" type="submit">Sign Up</div>
</form>
Here is my TS file
import { Component , OnInit} from '#angular/core';
import {FormControl, FormGroup, Validators} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app works!';
signupForm : FormGroup;
ngOnInit(){
this.signupForm = new FormGroup({
'email' : new FormControl('test#test.com')
});
// this.signupForm.valueChanges.subscribe(
// (value) => console.log(value)
// );
}
onSubmit(){
console.log(this.signupForm);
}
}
For some reason I cannot print anything on console which I am trying to do in OnSubmit method. I checked everything and it looked okay , but still nothing comes on console when I press the button.
Can anyone please help me what am I doing wrong ?

Attribute type is not a valid type on div element. This this case you will need to have an input or button with type submit for the callback to be triggered.
<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="email">Mail</label>
<input type="email"
name="email"
id="email"
formControlName="email"
class="form-control">
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>

Related

Hide side bar after login

I want a responsive page , when the login page is loaded it should hide the sidebar and should login page should span full page . After the user is login it should show the side bar with all the components. I tried few ways with the code below.
app.component.html:
<div class="row">
<div *ngIf="isLoggedUser == 'true'" class="col-lg-3 col-md-3 col-sm-3">
<app-sidebar></app-sidebar>
</div>
<div class="col-lg-9 col-md-9 col-sm-9">
<router-outlet></router-outlet>
</div>
</div>
app.component.ts
import { Component, OnInit, VERSION } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular ' + VERSION.major;
isLoggedUser: any;
ngOnInit() {
this.isLoggedUser = sessionStorage.getItem('isLogged');
if (sessionStorage.getItem('isLogged') === 'true') {
this.isLoggedUser = 'true';
} else {
this.isLoggedUser = 'false';
}
}
}
login.component.html
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" (click)="login()" class="btn btn-primary">Submit</button>
</form>
login.component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
isLoggedUser: any;
constructor(private router: Router) {}
ngOnInit() {
sessionStorage.setItem('isLogged', 'false');
}
login() {
this.isLoggedUser = sessionStorage.setItem('isLogged', 'true');
this.router.navigate(['/users']);
}
}
here I am trying to store a variable in session storage , before the user login the isLoggedUser flag will be false hence the sidebar will not be displayed . Once the user clicks the login the isLoggedUser will be made true , but the side bar is not displayed until I reload the page. Can someone please guide what is the bug/mistake in the code. And the page is not responsive for medium and small screens
StackBlitz (Demo) : stackblitz
Change the login method from login.component.ts to this one:
login() {
this.isLoggedUser = 'true';
sessionStorage.setItem('isLogged', 'true');
this.router.navigate(['/users']);
}
Note: sessionStorage.setItem('isLogged', 'true'); doesn't return anything so this.isLoggedUser was getting set to undefined
I just replaced
this.isLoggedUser = sessionStorage.setItem('isLogged', 'true');
with
this.isLoggedUser = 'true';
sessionStorage.setItem('isLogged', 'true');
Also need to have shared variable isLoggedUser so that when you update it in login component it's value will be refleted in app component also.

Submitting Angular form returns unavailable or undefined

I have written a registration page component in Angular. I have followed what few tutorials there are and I have stumbled upon a very frustrating bug. Pressing the submit button on the form will simply cause the console to print out "undefined" when trying to access the NgForm's value. Accessing the "valid" field of the NgForm will return true or false, as expected.
the page:
<app-players></app-players>
<div class="container" style="text-align:center">
<h3>Register a new account!</h3>
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<label>Username:</label> <input type="text" id="username"
required #username="ngModel"
name="username" ngModel><br>
<label>Password:</label> <input type="password" id="password"
required #password="ngModel"
name="password" ngModel><br>
<label>Email:</label> <input type="text" id="email"
required #email="ngModel"
name="email" ngModel><br>
<button type="submit" class="btn btn-success" [disabled]="!newPlayerEntry.form.valid">Submit</button>
</form>
</div>
<div id = "result">
</div>
The component:
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { NewPlayer } from './new-player';
#Component({
selector: 'app-players-register',
templateUrl: './players-register.component.html',
styleUrls: ['./players-register.component.css']
})
export class PlayersRegisterComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
onSubmit(f: NgForm) {
console.log(f.value);
}
}
You need remove [disabled]="!newPlayerEntry.form.valid" and change to [disabled]="!f.valid"
This is working version
https://stackblitz.com/edit/angular-mgmmsq?file=src%2Fapp%2Fapp.component.html

type script given error must supply value for formcontrol name id

I have been getting the following error:
ERROR Error: Must supply a value for form control with name: 'id'.
even though i have provided value for the same and here is my typescript code
import { Component, OnInit,Inject } from '#angular/core';
import {MatDialog,MatDialogRef,MAT_DIALOG_DATA} from '#angular/material';
import {FormGroup,FormBuilder,Validators} from '#angular/forms';
import {AdminService} from '../../services/admin.service';
#Component({
selector: 'app-subcategory-modal',
templateUrl: './subcategory-modal.component.html',
styleUrls: ['./subcategory-modal.component.css']
})
export class SubcategoryModalComponent implements OnInit {
subcategoryForm:FormGroup;
category:any;
constructor(public subCategoryDialogref:MatDialogRef<SubcategoryModalComponent>,#Inject(MAT_DIALOG_DATA)public data:string,private formBuilder:FormBuilder,private service:AdminService)
{
this.generateCategory();
}
ngOnInit() {
this.createForm();
this.generateSubcategory(this.data);
}
createForm()
{
this.subcategoryForm=this.formBuilder.group({
id:[null,Validators.required],
subcategoryName:[null,Validators.required],
category:[null,Validators.required]
});
}
generateSubcategory(data)
{
this.service.getSubcategorys(data).subscribe(res=>{
console.log(res.result);
this.subcategoryForm.setValue({
id:res.result.Name
});
},err=>{
});
}
generateCategory()
{
this.service.getCategory().subscribe(res=>{
this.category=res;
});
}
}
and this is my html code :-
<form [formGroup]="subcategoryForm">
<div class="form-group">
<input type="text" class="form-control" formControlName="id"value="" name="id">
</div>
<div class="form-group">
<input type="text" class="form-control" formControlName="subcategoryName" name="subcategoryName" >
</div>
<div class="form-group">
<select class="form-control" name="category" formControlName="category">
<option value="0">-Select-</option>
<option *ngFor="let data of category?.result" value="{{data.id}}">{{data.Name}}</option>
</select>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary" name="button">Update</button>
</div>
</form>
can anybody tell me where i'm going wrong? and why this error keeps happening?
Since you want to change only the value of the control id, you should use patchValue instead of setValue method to modify the value of that formControl.
this.subcategoryForm.patchValue({
id:res.result.Name
});
if you want to use setValue method, you can call it from the formControl id :
this.subcategoryForm.controls['id'].setValue(res.result.Name);

Angular 2 : ERROR TypeError: Cannot read property 'value' of undefined

I am getting the following error on browser console after clicking on Submit button.
In this application I am trying to get information about the Student uploaded code below.
I am unable to find why this error is shown on console.
I have correctly added the formControlName.
Component
import { Component, OnInit, Inject } from '#angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, AbstractControl } from '#angular/forms';
#Component({
selector: 'app-new-record',
templateUrl: './new-record.component.html',
styleUrls: ['./new-record.component.css']
})
export class NewRecordComponent implements OnInit {
myFormGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myFormGroup = this.formBuilder.group({
name: new FormControl('', Validators.compose([
Validators.required
])),
claz: new FormControl('BCA'),
admissionYear: new FormControl(Validators.compose([Validators.required]))
});
}
ngOnInit() {
}
onSubmit(student) {
console.log('onSubmit called !');
}
}
Template
<form [formGroup]="myFormGroup"
(ngSubmit)="onSubmit(form.value)">
<div class="form-group">
<label for="claz">Class:</label> <select name="claz" formControlName="claz">
<option value="MCA">MCA</option>
<option value="BCA">BCA</option>
<option value="M.Sc">M.Sc</option>
<option value="B.Tech">B.Tech</option>
</select>
</div>
<div class="form-group">
<label for="name">Name:</label> <input type="text"
class="form-control" id="name" formControlName="name">
</div>
<div class="form-group">
<label for="admissionYear">Admission Year:</label> <input type="number"
class="form-control" id="admissionYear" formControlName="admissionYear">
</div>
<button type="submit" class="btn btn-default" >Submit</button>
</form>
There is no form defined, instead use myFormGroup which has been defined as formGroup
(ngSubmit)="onSubmit(myFormGroup.value)"

I can't make an input be required with Angular2

I'm starting with Angular and I'm on a project where I have to validate the inputs so they can't be left clear, every input must me completed.
It's an html and we have a .ts file.
This is an extract of the html:
<div class="form-group">
<input type="text"
class="form-control"
id="factory"
[(ngModel)]="factory.company">
</div>
I need to validate this factory input but when I was watching tutorials all I needed to do was to write 'required' inside the <input> and that was it but I had a <form> and every input was inside this form, and this html doesn't have a <form> and when I put one the design was horrible and I couldn't work.
Here is an example using required fields (in login page) :
<form [formGroup]='loginForm' (submit)="login(loginForm.value)">
<div class="col-md-6">
<div class="login-mail">
<input type="text" placeholder="Email" formControlName="email" required="">
<i class="fa fa-envelope"></i>
</div>
<div class="login-mail">
<input type="password" placeholder="Password" formControlName="password" pattern=".{8,20}" required="">
<i class="fa fa-lock"></i>
</div>
</div>
<div class="col-md-6 login-do">
<label class="hvr-shutter-in-horizontal login-sub">
<input type="submit" value="login" >
</label>
</div>
<div class="clearfix"> </div>
</form>
in the login.component.ts , u should make some changes:
1) import some modules :
import { FormBuilder, FormGroup, Validators} from '#angular/forms';
2) in oninit function :
loginForm: FormGroup;
constructor(private fb : FormBuilder) {}
ngOnInit(){
this.loginForm = this.fb.group({
email : ["", Validators.required],
password : ["", Validators.required]
});
}
Hope that helps u :)
I would think that you should be able to add a form element. However, if you cannot as you have said then you can add the ngForm directive onto any element to achieve the same behavior as having the form element.
See this plunker for examples using ReactiveFormsModule and FormsModule:
Plunker
//our root app component
import {Component, OnInit, NgModule} from '#angular/core'
import {ReactiveFormsModule, FormsModule, FormControl, Validators} from '#angular/forms'
import {BrowserModule} from '#angular/platform-browser'
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div class="form-group">
<label>Model Driven Form</label>
<input type="text"
class="form-control"
id="companyModel"
[formControl]="companyModel">
<span [hidden]="companyModel.valid || companyModel.pristine">REQUIRED!</span>
</div>
<div class="form-group" ngForm #myForm="ngForm">
<label>Template Driven Form</label>
<input type="text"
class="form-control"
name="companyTemplate"
ngModel
id="companyTemplate"
#companyTemplate="ngModel"
required>
<span [hidden]="companyTemplate.valid || companyTemplate.pristine">REQUIRED!</span>
</div>
</div>
`,
})
export class App implements OnInit {
name:string;
companyModel: FormControl
constructor() {
this.name = 'Form Validation Demo'
}
ngOnInit() {
this.companyModel = new FormControl('', Validators.required)
}
}
#NgModule({
imports: [ BrowserModule, ReactiveFormsModule, FormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}

Categories