How can i validade a button click through an array of inputs? - javascript

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>

Related

Pass input text value to function per click

I want to insert the value inserted into an input in the database using Angular as the frontend and php as the backend but I'm not able to insert the input value into the method along with the user.id.
The input is for the reason of moderation when clicking on disapprove it is necessary to pass the reason but it is not entering.
import { Component, OnInit, TemplateRef } from '#angular/core';
import { FormGroup } from '#angular/forms';
import { observerMixin } from '#rodrigowba/observer-component';
import { ResponseData, DefaultResponse } from '#rodrigowba/http-common';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { ToastrService } from 'ngx-toastr';
import { Observable } from 'rxjs';
import { ActionPayload } from '~/ngrx';
import {
HotsiteUser,
HotsiteUsersFacade,
HotsiteUsersFormService,
RegistrationStatusTypes,
UpdateHotsiteUserRequest,
HotsitePointsPrebase,
} from '~/admin/users';
import {
updateHotsiteUser,
hotsiteUserUpdated,
hotsiteUserUpdateFailed,
hotsiteUserRegistrationModerated,
hotsiteUserModerateRegistrationFailed
} from '~/admin/users/state';
import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
#Component({
templateUrl: './view.component.html',
})
export class ViewComponent extends observerMixin() implements OnInit {
user$: Observable<HotsiteUser>;
pointsPrebase$: Observable<HotsitePointsPrebase[]>;
customFields$: Observable<{
field: string,
value: string
}[]>;
registrationStatusTypes = RegistrationStatusTypes;
form: FormGroup;
modalRef: BsModalRef;
submiting = false;
constructor(
private hotsiteUsersFacade: HotsiteUsersFacade,
private hotsiteUsersFormService: HotsiteUsersFormService,
private modalService: BsModalService,
private toastr: ToastrService
) {
super();
this.form = this.hotsiteUsersFormService.updateForm();
}
ngOnInit() {
this.user$ = this.hotsiteUsersFacade.selectCurrentHotsiteUser();
this.customFields$ = this.user$.pipe(
map(user => Object.values(user.custom_fields)),
map(customFields => customFields.map(customField => {
let value = customField.value;
if (Array.isArray(value)) {
value = value.join(', ');
}
return {
field: customField.field,
value
};
}))
);
this.pointsPrebase$ = this.user$.pipe(
map(user => user.id),
distinctUntilChanged(),
tap(id => {
this.hotsiteUsersFacade.fetchHotsitePointsPrebase(id);
}),
switchMap(id => this.hotsiteUsersFacade.selectHotsitePointsPrebaseByHotsiteUser(id))
);
this.observe(this.user$).subscribe(user => {
this.form.patchValue(user);
});
this.observe(
this.hotsiteUsersFacade.ofType(updateHotsiteUser)
).subscribe(() => {
this.submiting = true;
});
this.observe(
this.hotsiteUsersFacade.ofType<ActionPayload<ResponseData<HotsiteUser>>>(
hotsiteUserUpdated,
hotsiteUserRegistrationModerated
)
).subscribe(action => {
const { message, data } = action.payload;
this.submiting = false;
this.toastr.success(message);
});
this.observe(
this.hotsiteUsersFacade.ofType<ActionPayload<DefaultResponse>>(
hotsiteUserUpdateFailed,
hotsiteUserModerateRegistrationFailed
)
).subscribe(action => {
const { message } = action.payload;
this.submiting = false;
this.toastr.error(message);
});
}
onSubmit(id: string, data: UpdateHotsiteUserRequest) {
this.hotsiteUsersFacade.updateHotsiteUser(id, data);
}
openModal(template: TemplateRef<any>, size = 'modal-md') {
this.modalRef = this.modalService.show(template, { class: size });
}
approveRegistration(id: string,reason: string) {
this.hotsiteUsersFacade.moderateRegistrationHotsiteUser(id, { approved: true,reason });
}
rejectRegistration(id: string,reason: string) {
this.hotsiteUsersFacade.moderateRegistrationHotsiteUser(id, { approved: false,reason });
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<form [formGroup]="form" (ngSubmit)="onSubmit(user.id, form.value)" >
<form [formGroup]="form" (ngSubmit)="onSubmit(user.id, form.value)" >
<div class="row mb-3">
<div class="col-12">
<div class="form-group">
<label>Name</label>
<input type="text" [value]="user.name" class="form-control" readonly />
</div>
</div>
<div class="col-12 col-lg-6">
<div class="form-group">
<label>E-mail</label>
<input type="text" [value]="user.email" class="form-control" readonly />
</div>
</div>
<div class="col-12 col-lg-6">
<div class="form-group">
<label>Document</label>
<input type="text" [value]="user.document" class="form-control" readonly />
</div>
</div>
<div class="col-12" *ngFor="let customField of customFields$ | async">
<div class="form-group">
<label>{{ customField.field }}</label>
<input type="text" [value]="customField.value" class="form-control" readonly />
</div>
</div>
<div class="col-auto">
<div class="form-group">
<mat-slide-toggle formControlName="admin" color="primary" ></mat-slide-toggle>
<label class="ml-2">Admin</label>
</div>
</div>
<div class="col-auto">
<div class="form-group">
<mat-slide-toggle formControlName="active" color="primary" ></mat-slide-toggle>
<label class="ml-2">Active</label>
</div>
</div>
</div>
<ng-container *ngIf="pointsPrebase$ | async as pointsPrebase">
<div class="row mb-3" *ngIf="pointsPrebase.length > 0">
<div class="col-12">
<h4 class="font-16 font-weight-bold">Points</h4>
</div>
<div class="col-12 col-lg-6">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Chave</th>
<th class="text-center">Points</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let points of pointsPrebase">
<td>{{ points.value }}</td>
<td class="text-center">{{ points.points }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</ng-container>
<div class="form-row">
<ng-container *ngIf="user.registration_status === registrationStatusTypes.AwaitingModeration">
<div class="col-auto">
<label>Reason</label>
<input type="text" name="reason" placeholder="Reason of moderation..." class="form-control"/>
</div>
<div class="col-auto">
<button
type="button"
class="btn btn-success"
(click)="approveRegistration(user.id,form.reason)"
>
<app-loading-label [loading]="submiting">Approved </app-loading-label>
</button>
</div>
<div class="col-auto">
<button
type="button"
class="btn btn-danger"
(click)="rejectRegistration(user.id,form.reason)"
>
<app-loading-label [loading]="submiting">Repproved </app-loading-label>
</button>
</div>
</ng-container>
<div class="col text-right">
<button
type="submit"
class="btn btn-orange"
[disabled]="form.invalid || submiting"
>
<app-loading-label [loading]="submiting">Salvar</app-loading-label>
</button>
</div>
</div>
</form>
Error:
Property 'reason' does not exist on type 'formGroup'
As user776686 suggested, there is a formControlName missing linked to "reason" field.
To get the field value in HTML you should access to the FormGroup controls:
(click)="approveRegistration(user.id, form.controls.reason.value)"
Also you can create a "get" property in TS code and then access to it in HTML:
get reason() {
return this.form.controls.reason.value;
}
(click)="approveRegistration(user.id, reason)"
BTW, a field can be accessed too through the "get" method of a FormGroup:
get reason() {
return this.form.get('reason').value;
}
It expects a control with the attribute formControlName="reason" which is not present here:
<input type="text" name="reason" placeholder="Reason of moderation..." class="form-control"/>
This might be a reason.
If that doesn't help, you my also want to look into the *ngIf condition here:
<ng-container *ngIf="user.registration_status === registrationStatusTypes.AwaitingModeration">

Angular 8 - Upload multiple array of images using form builder

I have a product form with different fields like product name, description etc.. also array of images.
Product Form
product name product description
product purity product commodity
Images (Add)
checkbox 1 Image 1
checkbox 2 Image 2
checkbox 3 Image 3.
....
I can able to save in my database product name and product description and other fields but don't how to upload those images. Because images are created on clicking the add button and it may have one or as many images based on requirement.I have created the form using Form builder. Given my code below.
Template :
<form class="kt-form kt-form--group-seperator-dashed" [formGroup]="mmgForm">
<div class="kt-form__section kt-form__section--first">
<div class="kt-form__group">
<div class="row">
<label class="col-lg-2 col-form-label">Product Name:</label>
<div class="col-lg-4">
<mat-form-field class="example-full-width">
<input formControlName="prod_name" matInput placeholder="Enter product name" [ngClass]="{ 'is-invalid': submitted && mmgForm.controls['prod_name'].errors }">
<div *ngIf="submitted && mmgForm.controls['prod_name'].errors" class="invalid-feedback cls-formErr">
<div *ngIf="mmgForm.controls['prod_name'].errors.required">Product name is required</div>
</div>
</mat-form-field>
</div>
<label class="col-lg-2 col-form-label">Product description:</label>
<div class="col-lg-4">
<mat-form-field class="example-full-width">
<textarea formControlName="prod_description" matInput placeholder="Enter product description" rows="5" [ngClass]="{ 'is-invalid': submitted && mmgForm.controls['prod_description'].errors }"></textarea>
<div *ngIf="submitted && mmgForm.controls['prod_description'].errors" class="invalid-feedback cls-formErr">
<div *ngIf="mmgForm.controls['prod_description'].errors.required">Product description is required</div>
</div>
</mat-form-field>
</div>
</div>
</div>
<div class="product_images">
<div class="imageHeading">
<p>
Images (<button mat-icon-button color="primary" matTooltip="Add product" (click) = addImage()><mat-icon>add_circle</mat-icon></button>)
</p>
</div>
<div class="kt-form__group">
<div class="row">
<div class="col-lg-1 imageLabel">#</div>
<div class="col-lg-2 imageLabel">Main Image</div>
<div class="col-lg-3 imageLabel">Choose Image</div>
<div class="col-lg-2 imageLabel">Image</div>
<div class="col-lg-2 imageLabel">Actions</div>
</div>
</div>
<div class="imagesContainer">
<div class="kt-form__group image-container container-1" *ngFor="let image of images; index as i">
<div class="row">
<div class="col-lg-1">{{ i+1 }}</div>
<div class="col-lg-2"><input type="checkbox" /></div>
<div class="col-lg-3"><input type="file" accept="image/*" (change)="imagePreview($event, image)" /></div>
<div class="col-lg-2"><img [src]="image.url.imgUrl" class="prod_image" /></div>
<div class="col-lg-2">
<button mat-icon-button color="warn" matTooltip="Delete Product" type="button" (click)="deleteImage(i)">
<mat-icon>delete</mat-icon>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
Ts File :
// Angular
import { Component, OnInit, ElementRef, ViewChild, ChangeDetectionStrategy, OnDestroy, ChangeDetectorRef } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
// Material
import { SelectionModel } from '#angular/cdk/collections';
import { MatPaginator, MatSort, MatSnackBar, MatDialog, MatRadioButton } from '#angular/material';
import { ProductManagementService } from '../../../../../core/e-commerce/_services/product-management.service';
import { ToastrService } from 'ngx-toastr';
#Component({
selector: 'kt-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.scss'],
})
export class ProductEditComponent implements OnInit {
mmgForm : any;
fileData: File = null;
previewUrl : any = "/assets/media/images/noimage.jpg";
images : any = [];
constructor(
private products: ProductManagementService,
private router: Router,
private route: ActivatedRoute,
private toastr: ToastrService,
private cdr: ChangeDetectorRef,
private FB: FormBuilder,
) {
}
ngOnInit() {
this.createForm();
this.addImage();
}
createForm() {
this.mmgForm = this.FB.group({
prod_name: ['', Validators.required],
prod_description: ['', Validators.required]
});
}
/**
* Form Submit
*/
submit() {
if (this.mmgForm.invalid) {
console.log(this.mmgForm);
return;
}
const controls = this.mmgForm.controls;
var form_values = {
prod_name: controls.prod_name.value,
prod_description: controls.prod_description.value,
}
this.products
.createProduct(JSON.stringify(form_values)).subscribe( //Calling Service
(data) => {
console.log(data);
},
error => {
}
);
}
imagePreview(fileInput: any, image) {
this.fileData = <File>fileInput.target.files[0];
// Show preview
var mimeType = this.fileData.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
var reader = new FileReader();
reader.readAsDataURL(this.fileData);
reader.onload = (_event) => {
image.url.imgUrl = reader.result;
this.cdr.markForCheck();
}
}
addImage(){
let url = {imgUrl : this.previewUrl}
this.images.push({url});
}
deleteImage(index: number) {
this.images.splice(index, 1)
}
}
I would suggest to create a FileUploadService for that.
The Service method:
uploadFiles(Array<File> files): Observable<FileUploadResponse> {
const url = `your-upload-url`;
const formData: FormData = new FormData();
for(File file in files) {
formData.append('file', file, file.name);
}
return this.http.post<FileUploadResponse>(url, formData /*{headers if necessary}*/);
}
Your component.ts:
//[..]
Array<File> files = [];
onFileInputEvent(event: any) {
for(let i = 0; i < event.srcElement.files.length; i++) {
this.fileName = event.srcElement.files[0].name;
this.files.push(event.srcElement.files[0]);
}
}
uploadFiles(){
this.fileUploadService.uploadFile(this.file).subscribe(res => { // do something}, err =>{});
}
Your component.html:
<!-- [..] -->
<input id="fileInput" placeholder="Images" type="file" (change)="onFileInputEvent($event)" accept=".jpg">
Edit with a more beautiful input
<div class="file-input">
<input id="fileInput" placeholder="CSV-Datei" type="file" class="hidden" (change)="onFileInputEvent($event)" accept=".csv">
<label for="fileInput" class="mat-raised-button">Add images</label>
<mat-chip-list *ngIf="fileName">
<mat-chip [removable]="true" (removed)="remove()">
{{fileName}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>

angular reactive form add FormArray inside a nested FormGroup inside another FormArray inside another FormGroup

I've created the nested FormGroup (questionnaire) which contains a FormArray (section) which contains another FormGroup (creatSection()) that contains another FormArray (question) in which we have another formgroup (creatQuestion()) in which we have another formarray(answer) that has a formgroup (creatAnswer())
Everything appears fine unless I want to add another question or another answer nothing the addSection works fine
so the creation is ok but the problem in the add.
what I'm thinking about is when you create a question it doesn't know to where it's going to be put in but I couldn't figure out how to fix it
my questionnaire.ts looks like this
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormArray } from '#angular/forms'
#Component({
selector: 'app-questionnaire',
templateUrl: './questionnaire.component.html',
styleUrls: ['./questionnaire.component.css']
})
export class QuestionnaireComponent implements OnInit {
questionnaire:FormGroup;
section:FormArray;
question:FormArray;
answer:FormArray;
constructor(private fb:FormBuilder) { }
ngOnInit() {
this.questionnaire=this.fb.group({
questionnaireName: [''],
section : this.fb.array([this.creatSection()])
})
}
creatSection():FormGroup{
return this.fb.group({
sectionName:[''],
question:this.fb.array([this.creatQuestion()])
})
}
addSection(){
this.section=this.questionnaire.get('section') as FormArray;
this.section.push(this.creatSection());
}
creatQuestion():FormGroup{
return this.fb.group({
questionName:[''],
type:[''],
answer:this.fb.array([this.creatAnswer()])
})
}
addQuestion(){
this.question=this.creatSection().get('question') as FormArray;
this.question.push(this.creatQuestion());
}
creatAnswer():FormGroup{
return this.fb.group({
id:[''],
answerName:['']
})
}
addAnswer(){
this.answer=this.creatQuestion().get('answer') as FormArray;
this.answer.push(this.creatAnswer());
}
onSubmit(){
console.log(this.questionnaire.value);
}
}
and the questionnaire.html is like this
<h1>questionnaire bla bla</h1>
<!-- <app-section></app-section> -->
<form [formGroup]="questionnaire" (ngSubmit)="onSubmit()">
<input type="text" placeholder="questionnaire..." formControlName="questionnaireName">
<ng-container formArrayName="section">
<div [formGroupName]="i" *ngFor="let ques of questionnaire.get('section').controls;let i = index;">
<input placeholder="section..." formControlName="sectionName" type="text">
<button (click)="addSection()">add section</button>
<ng-container formArrayName="question">
<div [formGroupName]="j" *ngFor="let sec of creatSection().get('question').controls;let j=index;">
<input placeholder="question..." formControlName="questionName" type="text">
<input placeholder="type..." formControlName="type" type="text">
<button (click)="addQuestion()">add question</button>
<ng-container formArrayName="answer">
<div [formGroupName]="k" *ngFor="let ans of creatQuestion().get('answer').controls;let k=index;">
<input placeholder="réponse..." formControlName ="answerName" type="text">
<button (click)="addAnswer()">add answer</button>
</div>
</ng-container>
</div>
</ng-container>
</div>
</ng-container>
<button type="submit">submit</button>
</form>
{{questionnaire.value | json}}
First Don't call to creatSection() in the .html
//WRONG
<div [formGroupName]="j" *ngFor="let sec of creatSection().get('question').controls;let j=index;">
//OK
<div [formGroupName]="j" *ngFor="let sec of ques.get('question').controls;let j=index;">
Well you need pass as argument the "indexs" of the arrays (I called "clasic way"), but you can also pass the group of the array itself
<button (click)="addAnswer(i,j)">add answer</button>
//or
<button (click)="addAnswer(sec)">add answer</button>
In a "clasic"
addAnswer(i:number:j:number)
{
const arraySection=((this.questionnaire.get('section') as FormArray)
const groupQuestion=(arraySection.get('question') as FormArray).at(i)
const arrayAnswer=groupQuestion.get('answer') as FormArray
arrayAnswer.push(this.creatAnswer())
}
If you pass the array itself
addAnswer(groupQuestion:FormArray)
{
const arrayAnswer=groupQuestion.get('answer') as FormArray
arrayAnswer.push(this.creatAnswer())
}
NOTE: with a stackblitz was easer check and it's possible eror in my code, please get it the idea
thanks to #Eliseo the result would look like
questionnaire.html
<h1>questionnaire bla bla</h1>
<form [formGroup]="questionnaire" (ngSubmit)="onSubmit()">
<input type="text" placeholder="questionnaire..." formControlName="questionnaireName">
<ng-container formArrayName="section">
<div [formGroupName]="i" *ngFor="let ques of questionnaire.get('section').controls;let i = index;">
<input placeholder="section..." formControlName="sectionName" type="text">
<button (click)="addSection()">add section</button>
<ng-container formArrayName="question">
<div [formGroupName]="j" *ngFor="let sec of ques.get('question').controls;let j=index;">
<input placeholder="question..." formControlName="questionName" type="text">
<input placeholder="type..." formControlName="type" type="text">
<button (click)="addQuestion(ques)">add question</button>
<ng-container formArrayName="answer">
<div [formGroupName]="k" *ngFor="let ans of sec.get('answer').controls;let k=index;">
<input placeholder="réponse..." formControlName ="answerName" type="text">
<button (click)="addAnswer(sec)">add answer</button>
</div>
</ng-container>
</div>
</ng-container>
</div>
</ng-container>
<button type="submit">submit</button>
</form>
{{questionnaire.value | json}}
and questionnaire.ts would look like this
import { Component,OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormArray } from '#angular/forms'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
questionnaire:FormGroup;
section:FormArray;
question:FormArray;
answer:FormArray;
constructor(private fb:FormBuilder) { }
ngOnInit() {
this.questionnaire=this.fb.group({
questionnaireName: [''],
section : this.fb.array([this.creatSection()])
})
}
creatSection():FormGroup{
return this.fb.group({
sectionName:[''],
question:this.fb.array([this.creatQuestion()])
})
}
addSection(){
this.section=this.questionnaire.get('section') as FormArray;
this.section.push(this.creatSection());
}
creatQuestion():FormGroup{
return this.fb.group({
questionName:[''],
type:[''],
answer:this.fb.array([this.creatAnswer()])
})
}
addQuestion(groupSection:FormArray){
const arrayQuestion=groupSection.get('question') as FormArray
arrayQuestion.push(this.creatQuestion())
}
creatAnswer():FormGroup{
return this.fb.group({
id:[''],
answerName:['']
})
}
addAnswer(groupQuestion:FormArray){
const arrayAnswer=groupQuestion.get('answer') as FormArray
arrayAnswer.push(this.creatAnswer())
}
onSubmit(){
console.log(this.questionnaire.value);
}
}

How to display recieved form input data to other component in Angular 6?

register.component.html (the form input component)
<div class="card-content">
<form #registerForm="ngForm" (ngSubmit)="onSubmit(Name.value, Email.value)">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="Name"
#Name
ngModel required>
<label for="Name">Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">mail_outline</i>
<input type="text" name="Email"
#Email
ngModel
required
[pattern]="emailPattern">
<label for="Email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<button class="btn-large btn-submit"
type="submit"
[disabled]='!registerForm.valid'>Start</button>
</div>
</div>
</form>
</div>
register.component.ts
........................................................................................
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { QuizService } from '../shared/quiz.service';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
emailPattern = '^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$';
constructor(private route: Router, private quiz: QuizService) { }
user = {
username: '',
email: ''
};
ngOnInit() {
}
onSubmit(name, email) {
this.user.username = name;
this.user.email = email;
this.route.navigate(['quiz']);
console.log(this.user.username, this.user.email); // log works!!
}
}
quiz.component.html (here i want to display the data which user entered in register component)
.........................................................
<div class="row">
<div class="col s6 offset-s3">
<h3>Welcome to quiz</h3>
<b>Your Name is: </b>
<br>
<b>Your Email is: </b>
</div>
</div>
this.route.navigate(['quiz',{username:username,...}])
and in your quiz component receive data
this.route.params.subscribe(params=>{ console.log(params.username)})
don't forget inject the ActivatedRoute in your quiz
constructor(private route:ActivatedRoute)
There are many way to accomplish this but I would suggest looking at NgRX Store, if you want a simpler solution then you can use a service:
#Injectable({
provideIn: ‘root’
})
export class SomeService {
userSubject = new BehaviorSubject<User>({});
user$: Observable<User> = this.userSubject;
}
In your RegisterComponent submit event you will call someService.userSubject.next(this.user); and in your QuizComponent subscribe to someService.user$ to pick up the data

getresponse recaptcha in angular 4 form

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() {}
}

Categories