I am new in angular and I want to know how to change property disabled in a button, with get-response recaptcha in angular 4 form.component
I try with this but not working:
<div class="login-page">
<div class="form">
<form class="login-form">
<input type="text" placeholder="Usuario" required/>
<input type="password" placeholder="Contraseña" required/>
<div >
<re-captcha class="g-recaptcha" (resolved)="resolved($event)"
siteKey="6LcOuyYTAAAAAHTjFuqhA52fmfJ_j5iFk5PsfXaU">
</re-captcha>
</div>
<button id="entrarbtn" onclick="captcha;" (click)="submit()" type="submit"
disabled>Entrar</button>
<p class="message">No se ha registrado? <a href="/registrar">Cree una
cuenta</a>
</p>
<script>
var captcha = function ()
{var response = grecaptcha.getResponse();
if(response.length == 0)
{return false;}
else
{$("#entarbtn").prop("disable"), false;
return true;
}};
</script>
</form>
</div>
</div>
in login.component.ts
import { Component, OnInit } from '#angular/core';
import {Router} from "#angular/router";
export interface FormModel {
captcha?: string;}
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public submit(): void {this.router.navigate(['/pagina']);}
constructor(private router: Router)
{ }
ngOnInit() {}
}
Related
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.
I have an array of inputs:
<div id="playerZone" *ngFor="let player of team;let i=index">
<div id="buttonZone">
<div class="buttonsAdd">
<mat-form-field appearance="outline" #f="ngForm">
<mat-label>Summoner Name</mat-label>
<label>
<input matInput placeholder="Placeholder"
(change)="updatePlayerSumonerName($event,i)">
</label>
</mat-form-field>
</div>
</div>
<button mat-raised-button routerLink="/waiting" [disabled]="" (click)="placeOnTheList()" hidden="">Waiting Room</button>
And a button that i only want to enable if all inputs are filled, and i dont know how to do that.
I need some guidance.
I could create variables that get to true when the input is written, but i know that is a better way of do that
updatePlayerSumonerName(name,i){
console.log(name.target.value);
this.team[i].summonerName = name.target.value;
}
You can achieve ur requirement as below.
Please check this Demo
in your app.component.ts,
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, FormArray, Validators, FormBuilder } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
players = [
'player1',
'player2',
'player3',
'player4'
];
constructor(private fb: FormBuilder) { }
form = this.fb.group({
team: new FormArray([])
});
ngOnInit() {
this.addPlayers(this.players);
}
get team(): FormArray {
return this.form.get('team') as FormArray;
}
onFormSubmit(): void {
for (let i = 0; i < this.team.length; i++) {
console.log(this.team.at(i).value);
}
}
addPlayers(players: string[]): void {
players.forEach(player => {
this.team.push(new FormControl(player, [Validators.required]));
});
}
}
and app.component.html,
<div class="container">
<br>
<form [formGroup]="form" (ngSubmit)="onFormSubmit()">
<div formArrayName="team">
<div class="form-group row">
<label for="commessa" class="col-sm-2 col-form-label">Team</label>
<div class="col-sm-10">
<ng-container *ngFor="let player of team.controls; index as idx">
<div class="row">
<div class="col-sm-8">
<input type="text" [ngClass]="{'error':player.invalid && player.touched}"
[formControlName]="idx" class="form-control" id="commessa">
</div>
</div>
</ng-container>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary" [disabled]="form.invalid">Save</button>
</div>
</form>
</div>
I'am new to angular 8.
I'am currently doing a small assignment for college but with this all Covid 19 thing happening communication with the lecture is limited and because of this is slowing my down.
I googled the error for ages and cant seem to find whats wrong.
Thanks.
<button (click)="show = !show">{{show ? 'Hide' : 'Add a car'}}</button>
<div *ngIf="show">
<form>
<label>Make</label>
<input type="text" name="make" placeholder="Enter Make" #make>
<label>Model</label>
<input type="text" name="model" placeholder="Enter Model" #model>
<label>Year</label>
<input type="text" name="year" placeholder="Enter Year" #year>
<button type="submit" (click)="addTheCar(make.value,
model.value,year.value)">Add the Car</button>
</form>
</div>
<div class="container">
<app-car *ngFor="let carData of carsData" [carData]="carData"></app-car>
</div>
This is the carlist.component.html(where the error sends me)
import { Component, OnInit } from '#angular/core';
import { ICar, Car } from '../interfaces/car';
import { CarApiService } from '../services/car-api.service';
#Component({
selector: 'app-carlist',
templateUrl: './carlist.component.html',
styleUrls: ['./carlist.component.css'],
providers: [CarApiService]
})
export class CarlistComponent implements OnInit {
carsData: ICar[];
constructor(private _carAPIService:CarApiService) { }
ngOnInit(): void{
this._carAPIService.getCarData().subscribe(carsData =>
{this.carsData = carsData});
}
addTheCar(make:string, model:string, year:string):boolean{
let tempCar:ICar;
tempCar= new Car(make,model,year);
this._carAPIService.addCarData(tempCar);
return false;
}
}
You have to define show in CarlistComponent.ts
export class CarlistComponent implements OnInit {
show:boolean;
It is what it says: there is no show property on your component. Add show = false; under your carsData line and it should go away.
try this
import { Component, OnInit } from '#angular/core';
import { ICar, Car } from '../interfaces/car';
import { CarApiService } from '../services/car-api.service';
#Component({
selector: 'app-carlist',
templateUrl: './carlist.component.html',
styleUrls: ['./carlist.component.css'],
providers: [CarApiService]
})
export class CarlistComponent implements OnInit {
carsData: ICar[];
show:boolean;
constructor(private _carAPIService:CarApiService) { }
ngOnInit(): void{
this._carAPIService.getCarData().subscribe(carsData =>
{this.carsData = carsData});
}
addTheCar(make:string, model:string, year:string):boolean{
let tempCar:ICar;
tempCar= new Car(make,model,year);
this._carAPIService.addCarData(tempCar);
return false;
}
}
specify a boolean value for show
export class CarlistComponent implements OnInit {
public show = true;
Only when show = true this div will get executed
<div *ngIf="show">
<form>
<label>Make</label>
<input type="text" name="make" placeholder="Enter Make" #make>
<label>Model</label>
<input type="text" name="model" placeholder="Enter Model" #model>
<label>Year</label>
<input type="text" name="year" placeholder="Enter Year" #year>
<button type="submit" (click)="addTheCar(make.value,
model.value,year.value)">Add the Car</button>
</form>
</div>
Please help me to solve this problem.
signup.component.html
<main role="main" class="container">
<h1 class="mt-5"> </h1>
<h5 class="mt-5">Create Account</h5>
<br/>
<div class="loader" *ngIf="dataLoading"></div>
<div class="alert alert-danger" role="alert" *ngIf="error">
An error occured. Here is the error {{errorMessage}}
</div>
<div *ngIf="savedChanges else showForm">
New Account is created. Please login.
<button class="btn btn-log btn-primary btn-block" routerLink="/login">Login</button>
</div>
<ng-template #showForm>
<span class="lead">
<form class="formsignin" #newUserForm="ngForm" (ngSubmit)="setUser(newUserForm.value)">
<div class="form-label-group">
<input type="text" name=inputEmail id="inputEmail" class="form-control" placeholder="Email" #inputEmail="ngModel" autofocus required email ngModel >
</div>
<div class="alert alert-danger" role="alert" *ngIf="inputEmail.invalid && (inputEmail.dirty || inputEmail.touched)">
Please enter a valid email.
</div>
<div class="form-label-group">
<input type="password" name=inputPassword id="inputPassword" class="form-control" placeholder="Password" #inputPassword="ngModel" autofocus required minlength="3" maxlength="15" ngModel >
</div>
<div class="alert alert-danger" role="alert" *ngIf="inputPassword.invalid && (inputPassword.dirty || inputPassword.touched)">
Please enter a valid password.
</div>
<br/>
<div *ngIf="!newUserForm.valid else showSubmitButton">
<button class="btn btn-lg btn-block btn-block" type="submit" disabled>Sign up</button>
</div>
<ng-template>
<button class="btn btn-lg btn-block btn-block" type="submit">Sign up</button>
</ng-template>
<p class="mt-5 mb-3 text-muted text-center">
<a routerLink="/login">Login</a>
</p>
</form>
</span>
</ng-template>
</main>
In html form i am just writing a only two input fields email and password and take it some validations that's it.
signup.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { BackendService } from '../services/backend.service';
import { Route } from '#angular/compiler/src/core';
#Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit, OnDestroy{
error:boolean = false;
errorMessage:String = "";
dataLoading:boolean = false;
private querySubscription;
saveChanges:boolean = false;
constructor(private _backendService:BackendService, private _route:Route) { }
ngOnInit() {
}
setUser(formData){
this.dataLoading = true;
this.querySubscription = this._backendService.setUser(formData).subscribe(
(res)=>{
if(res["errorCode"]>0){
this.error = false;
this.errorMessage = "";
this.dataLoading = false;
this.saveChanges = true;
}else{
this.error = true;
this.errorMessage = res["errorMessage"];
this.dataLoading = false;
}
},
(error)=>{
this.error = true;
this.errorMessage = error.message;
this.dataLoading = false;
},
()=>{
this.dataLoading = false;
}
);
}
ngOnDestroy(){
if(this.querySubscription){
this.querySubscription.unsbscribe();
}
}
}
In signup.component.ts file i am just checking the input field are validate or not if yes then go to the next procedure.
backend.service.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class BackendService {
constructor() { }
setUser(formData){
let fakeResponse = {
"errorCode" : 1,
"errorMessage" : "User Created",
"rowCount" : 30,
"data":{
"taken" : "abcd"
}
};
let fakeResponse_1 = {
"errorCode" : 0,
"errorMessage" : "Some error",
"rowCount" : 30,
"data":{
"taken" : "abcd"
}
};
return Observable.create(
observer =>{
setTimeout(()=>{
observer.next(fakeResponse_1)
}
,2000)});
}
}
In service file checking the user data and return the some output.
I am just creating a simple login form using some validations but i got some errors.
I don't know what happens there,
please help me to solve this error.
Hello Rushikesh Gadekar,
Your Problem is that Angular doesn't provide your backend-service for the constructor of your signup-component.
To solve this Problem you have to go to:
app.module.ts
And insert your Service to your providors.
Here's an Example how this could look like.
import { MyDataService } from './service/my-data/my-data.service';
import { ControlService } from './service/control/control.service';
import { ViewListService } from './service/view-list/view-list.service';
import { DevDataService } from './service/dev-data/dev-data.service';
#NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
ControlService,
MyDataService,
ViewListService,
DevDataService,
],
bootstrap: [...]
})
export class AppModule { }
I have a problem with dialog from angular material, when i press button to open it, it does, but not rly. Dialog does not show up but console prints 'open' and 'close', no errors
Dialog component
import {Component, Inject} from '#angular/core';
import {RssFeed} from "../model/rssFeed";
import {MAT_DIALOG_DATA, MatDialogRef} from "#angular/material";
import {AppService} from "../service/app.service";
#Component({
selector: 'app-new-feed-dialog',
templateUrl: './new-feed-dialog.component.html',
styleUrls: ['./new-feed-dialog.component.css']
})
export class NewFeedDialogComponent {
rssFeed: RssFeed = new RssFeed();
constructor(private service: AppService,
public dialogRef: MatDialogRef<NewFeedDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
}
onSaveClick(): void {
this.service.saveRssFeed(this.rssFeed)
this.dialogRef.close(this.rssFeed);
}
onCancelClick(): void {
this.dialogRef.close();
}
}
html
<h2 mat-dialog-title>
<mat-icon>library_add</mat-icon>
New Feed
</h2>
<mat-dialog-content>
<form>
<mat-form-field class="full-width">
<input matInput placeholder="Feed Name" name="name" [(ngModel)]="rssFeed.name">
</mat-form-field>
<mat-form-field class="full-width">
<input matInput placeholder="Feed Url" name="url" [(ngModel)]="rssFeed.url">
</mat-form-field>
</form>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button (click)="onCancelClick()">Cancel</button>
<button mat-button (click)="onSaveClick()">Save</button>
</mat-dialog-actions>
I'm opening it from another component
onAddRssFeedClick(): void{
let dialogRef = this.dialog.open(NewFeedDialogComponent)
dialogRef.afterOpen().subscribe( ()=> {
console.log('open')
})
dialogRef.afterClosed().subscribe(() => {
console.log('close')
});
}
In your app.component.html, there is the button that triggers your modal <a class="nav-link" (click)="onAddRssFeedClick()" href="#">Add Feed</a>
Remove the href="#" and you're good!