I get this error when i click login button in my login page
: this error is here :
Cannot read properties of undefined (reading 'include') when i call
window.location.reload();
what is the problem, I searched but did not find the problem
I am thankful with your guidance
my ts code is here :
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../_services/auth.service';
import { TokenStorageService } from '../_services/token-storage.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: any = {
username: null,
password: null
};
isLoggedIn = false;
isLoginFailed = false;
errorMessage = '';
roles: string[] = [];
constructor(private authService: AuthService, private tokenStorage: TokenStorageService) { }
ngOnInit(): void {
if (this.tokenStorage.getToken()) {
this.isLoggedIn = true;
this.roles = this.tokenStorage.getUser().roles;
}
}
onSubmit(): void {
const { username, password } = this.form;
this.authService.login(username, password).subscribe(
data => {
this.tokenStorage.saveToken(data.accessToken);
this.tokenStorage.saveUser(data);
this.isLoginFailed = false;
this.isLoggedIn = true;
this.roles = this.tokenStorage.getUser().roles;
this.reloadPage();
},
err => {
this.errorMessage = err.error.message;
this.isLoginFailed = true;
}
);
}
reloadPage(): void {
window.location.reload();
}
}
and my html code is
<div id="image">
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-10 col-md-8 col-lg-6 col-xl-5 p-5 ">
<mat-card>
<mat-card-header >
<mat-card-title> </mat-card-title>
</mat-card-header>
<mat-card-content>
<img src="https://s4.uupload.ir/files/user3_r3fq.png" class="p-2">
<form *ngIf="!isLoggedIn"
name="form"
(ngSubmit)="f.form.valid && onSubmit()"
#f="ngForm"
novalidate
>
<div class="form-group justify-content-center ">
<mat-form-field >
<label for="username"></label>
<i class="fa fa-user icon"></i>
<input matInput
type="text"
name="username"
placeholder="Username"
[(ngModel)]="form.username"
required
#username="ngModel"
/></mat-form-field>
<div id="mes"
role="alert"
*ngIf="username.errors && f.submitted"
>
please enter user name
</div>
</div>
<div class="form-group"> <mat-form-field>
<label for="password"></label>
<input matInput
type="password"
placeholder="Password"
name="password"
[(ngModel)]="form.password"
required
minlength="4"
#password="ngModel"
/>
</mat-form-field>
<div
role="alert"
*ngIf="password.errors && f.submitted"
>
<div id="mes" *ngIf="password.errors.required">Please Enter pass</div>
<div *ngIf="password.errors.minlength">
Password must be at least 6 characters
</div>
</div>
</div>
<div >
<button mat-raised-button class="btn btn-primary" >
<span>Login</span>
</button>
</div>
<div >
<div
role="alert"
*ngIf="f.submitted && isLoginFailed"
>
Login failed: {{ errorMessage }}
</div>
</div>
</form>
</mat-card-content>
</mat-card>
<div *ngIf="isLoggedIn">
Logged in as {{ roles }}.
</div>
</div>
</div>
</div>
</div>
and my user.service.ts is
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
const API_URL = 'http://localhost:8080/api/test/';
#Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
getPublicContent(): Observable<any> {
return this.http.get(API_URL + 'all', { responseType: 'text' });
}
getUserBoard(): Observable<any> {
return this.http.get(API_URL + 'user', { responseType: 'text' });
}
getModeratorBoard(): Observable<any> {
return this.http.get(API_URL + 'mod', { responseType: 'text' });
}
getAdminBoard(): Observable<any> {
return this.http.get(API_URL + 'admin', { responseType: 'text' });
}
}
and my auth.service.ts is
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
const AUTH_API = 'http://192.168.1.135:8282/api/Users/authenticate';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable({
providedIn: 'root'
})
export class AuthService {
m:any;
constructor(private http: HttpClient) { }
login(username: string, password: string): Observable<any> {
this.m= this.http.post(AUTH_API , {username,password}, httpOptions);
console.log(this.m);
return this.m;
}
register(username: string, email: string, password: string): Observable<any> {
return this.http.post(AUTH_API + 'signup', {
username,
email,
password
}, httpOptions);
}
}
Seem you have issues in this line, you need to check if getUser is returning what you need. To suppress the error you need to change:
this.roles = this.tokenStorage.getUser().roles;
Try changing to:
this.roles = this.tokenStorage.getUser()?.roles;
Related
I have a form with a text input and then I want to add a select inside that Form:
The select is an array:
typeAlert: TypeAlert[] = [
{ value: 'MEDICAL'},
{ value: 'POLICE'},
{ value: 'FIRE'}
];
I want to bind the value selected on the select. I have a var called select to store which the user has selected. I have to add the selected inside formGroup?
Also I am getting this error:
ngModel cannot be used to register form controls with a parent formGroup directive
component.html
<form class="container" [formGroup]="alertForm">
<div class="actions">
<div class="action" [routerLink]="['/alertes']">
<span>Torna a Alertes</span>
</div>
<div class="space"></div>
<button class="action" (click)="save()" [disabled]="!alertForm.valid">
Guardar
</button>
</div>
<div class="dades">
<div class="card">
<div class="card-title">
<b>Title</b>
</div>
<div class="card-content">
<mat-form-field>
<mat-label>Title</mat-label>
<input formControlName="title" matInput>
</mat-form-field>
</div>
</div>
</div>
<div class="dades">
<div class="card">
<div class="card-title">
<b>Type Alert</b>
</div>
<div class="card-content">
<mat-form-field appearance="fill">
<mat-label>Type Alert</mat-label>
<mat-select [(ngModel)]="selected">
<mat-option *ngFor="let alert of typeAlert" [value]="alert.value">
{{alert.value}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</div>
</div>
</form>
component.ts:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { FormGroup, FormControl, FormArray, Validators } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { AlertesService } from 'src/app/core/services/alertes.service';
import { MatDialog } from '#angular/material/dialog';
import { DialogNotificationsComponent } from 'src/app/shared/components/dialog-notifications/dialog-notifications.component';
interface TypeAlert {
value: string;
}
#Component({
selector: 'app-alert',
templateUrl: './alert.component.html',
styleUrls: ['./alert.component.scss']
})
export class AlertComponent implements OnInit, OnDestroy {
typeAlert: TypeAlert[] = [
{ value: 'MEDICAL'},
{ value: 'POLICE'},
{ value: 'FIRE'}
];
selected: string = this.typeAlert[0].value;
alertForm: FormGroup;
alert;
constructor(
private alertesService: AlertesService,
private route: ActivatedRoute,
private router: Router,
public dialog: MatDialog
) { }
ngOnInit() {
this.alert = this.route.snapshot.data.alert;
this.initForm();
}
ngOnDestroy() {
}
initForm() {
this.alertForm = new FormGroup({
title: new FormControl(this.alert ? this.alert.title : '', [Validators.required]),
});
}
save() {
console.log(this.selected);
if(this.alert) {
this.alertesService.update(this.alert._id, this.alertForm.value).subscribe(() => {
this.router.navigate(['/alertes'])
})
}
else {
const dialogRef = this.dialog.open(DialogNotificationsComponent, {
width: '600px',
data: {title: "Nova alerta", msg: this.alertForm.value.title}
});
dialogRef.afterClosed().subscribe(result => {
console.log(result);
if(result != undefined && result != null) {
this.alertesService.create({
notification: result ? result: null,
...this.alertForm.value
}).subscribe(() => {
this.router.navigate(['/alertes'])
})
}
});
}
}
}
You should [formControlName] with form groups, instead of ngmodel.
Please check https://angular.io/api/forms/FormControlName
I am a beginner in Angular.
I have created a demo app.
below is my code
servers.component.ts
import { Component, OnInit, Input } from '#angular/core';
import { Server } from './server.model';
#Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css'],
})
export class ServersComponent implements OnInit {
allowNewServer = false;
serverCreationStatus = 'no server created';
serverName = '';
ipAddress = '';
owner = '';
server: Server[] = [];
serverCreated = false;
constructor() {
}
ngOnInit(): void {}
onCreateServer() {
this.serverCreated = true;
this.serverCreationStatus = 'server created';
this.server_list.push(server;
}
}
I have one model file where i have declared one class and constructor to create server
server.model.ts
export class Server {
public serverName: string;
public ipAddress: string;
public owner: string;
constructor(ame: string, ip: string, owner: string) {
this.serverName = name;
this.ipAddress = ip;
this.owner = owner;
}
}
in servers.component.html i am using ngModel to bind object property with forms field
servers.component.html
<form action="">
<div class="row">
<label for="serverName" class="col-sm-2">Server Name</label>
<input
type="text"
class="form-control col-sm-10"
[(ngModel)]="server.serverName"
[ngModelOptions]="{ standalone: true }"
/>
</div>
<div class="row">
<label for="ipAddress" class="col-sm-2">IP Adress</label>
<input
type="text"
class="form-control col-sm-10"
[(ngModel)]="server.ipAddress"
[ngModelOptions]="{ standalone: true }"
/>
</div>
<div class="row">
<label for="owner" class="col-sm-2">Owner</label>
<input
type="text"
class="form-control col-sm-10"
[(ngModel)]="server.owner"
[ngModelOptions]="{ standalone: true }"
/>
</div>
<button
class="btn btn-primary"
[disabled]="!allowNewServer"
(click)="onCreateServer()"
>
Add server
</button>
</form>
<app-server *ngFor="let s of server" [data]="s"> </app-server>
and my child component `server.component.ts`
import { Component, Input } from '#angular/core';
import { Server } from '../servers/server.model';
#Component({
selector: 'app-server',
templateUrl: './server.component.html',
styles: [
`
.online {
color: white;
}
`,
],
})
export class ServerComponent {
serverStatus = 'offline';
#Input() data: Server;
constructor() {
this.serverStatus = Math.random() > 0.5 ? 'online' : 'offline;';
}
getColor() {
return this.serverStatus === 'online' ? 'green' : 'red';
}
}
my server.component.html
<p
[ngStyle]="{ backgroundColor: getColor() }"
[ngClass]="{ online: serverStatus === 'online' }"
>
Server created with name {{ data }}
</p>
i am gettig two error in above code
when using ngModel in servers.component.html
error TS2339: Property 'ipAddress' does not exist on type 'Server[]'.
34 [(ngModel)]="server.ipAddress"
getting this error for all field
2.not able to display created server data (not able to pass object data to child component)
calling child component in servers.component.html
Please help.
Thanks in advance
You have too many typos and errors, Here is the updated servers and server component classes, Compare this with your question and you can figure out the differences and errors. Hope this works !!
servers.component .ts & .html:
.html:
<form action="">
<div class="row">
<label for="serverName" class="col-sm-6">Server Name</label>
<input
id="serverName"
type="text"
class="form-control col-sm-10"
[(ngModel)]="serverName"
[ngModelOptions]="{ standalone: true }"
/>
</div>
<div class="row">
<label for="ipAddress" class="col-sm-6">IP Adress</label>
<input
id="ipAddress"
type="text"
class="form-control col-sm-10"
[(ngModel)]="ipAddress"
[ngModelOptions]="{ standalone: true }"
/>
</div>
<div class="row">
<label for="owner" class="col-sm-6">Owner</label>
<input
id="owner"
type="text"
class="form-control col-sm-10"
[(ngModel)]="owner"
[ngModelOptions]="{ standalone: true }"
/>
</div>
<button
class="btn btn-primary"
(click)="onCreateServer()">
Add server
</button>
</form>
<app-server *ngFor="let s of server" [data]="s"> </app-server>
.ts:
import { Component, OnInit } from '#angular/core';
import {Server} from '../../models/Server.model';
#Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
allowNewServer = false;
serverCreationStatus = 'no server created';
serverName = '';
ipAddress = '';
owner = '';
server: Server[] = [];
serverCreated = false;
constructor() {
}
ngOnInit(): void {}
onCreateServer() {
this.serverCreated = true;
this.serverCreationStatus = 'server created';
this.server.push(new Server(this.serverName, this.ipAddress, this.owner));
}
}
server.component .ts & .html:
.html:
<p
[ngStyle]="{ backgroundColor: getColor() }"
[ngClass]="{ online: serverStatus === 'online' }">
Server created with name {{ data.serverName }}
</p>
.ts:
import {Component, Input} from '#angular/core';
import {Server} from '../../models/Server.model';
#Component({
selector: 'app-server',
templateUrl: './server.component.html',
styleUrls: ['./server.component.css']
})
export class ServerComponent {
#Input() data: Server;
serverStatus = 'offline';
constructor() {
this.serverStatus = Math.random() > 0.5 ? 'online' : 'offline;';
}
getColor() {
return this.serverStatus === 'online' ? 'green' : 'red';
}
}
finally Server model class:
export class Server {
public serverName: string;
public ipAddress: string;
public owner: string;
constructor(name: string, ipAddress: string, owner: string) {
this.serverName = name;
this.ipAddress = ipAddress;
this.owner = owner;
}
}
Below is my Component :
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HttpService } from './http.service';
import { ProjectidService } from './projectid.service';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
projectDetailForm: FormGroup;
public submitted = false;
constructor(private fb: FormBuilder, private projectidvalidator: ProjectidService) { }
ngOnInit() {
this.projectDetailForm = this.fb.group({
projectid: ['', [Validators.required], [this.projectidvalidator.validate.bind(this.projectidvalidator)]],
projectname: ['name', Validators.required]
})
}
get f() { return this.projectDetailForm.controls; }
get validprojectid() { return this.projectDetailForm.get('projectid'); }
onSubmit(form: FormGroup) {
this.submitted = true;
// stop here if form is invalid
if (this.projectDetailForm.invalid) {
return;
}
console.log('Valid?', this.projectDetailForm.valid); // true or false
console.log('ID', this.projectDetailForm.value.projectid);
console.log('Name', this.projectDetailForm.value.projectname);
}
}
My Service :
import { Injectable } from '#angular/core';
import { Observable, of } from 'rxjs';
import { delay, tap, debounceTime } from 'rxjs/operators';
#Injectable()
export class HttpService {
constructor() { }
checkProjectID(id): Observable<any> {
// Here I will have valid HTTP service call to check the data
return of(true)
}
}
My Async validator :
import { HttpService } from './http.service';
import { Injectable } from '#angular/core';
import { AsyncValidator, AbstractControl, ValidationErrors } from '#angular/forms';
import { Observable, of } from 'rxjs';
import { map, catchError, debounceTime, switchMap } from 'rxjs/operators';
#Injectable()
export class ProjectidService {
constructor(private _httpService:HttpService) { }
validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
console.log(control.value);
return control.valueChanges.pipe(
debounceTime(500),
switchMap(_ => this._httpService.checkProjectID(control.value).pipe(
map(isTaken => {
console.log(isTaken);
if (isTaken) {
return { noproject: true }
} else {
return null
}
})
)),
catchError(() => null)
);
}
}
and template :
<form [formGroup]="projectDetailForm" name="projectdetails" (ngSubmit)="onSubmit(projectDetailForm)">
<div class="form-group">
<label for="id">Project ID</label>
<input type="text" class="form-control" id="id" [ngClass]="{ 'is-invalid': f.projectid.invalid && (f.projectid.dirty || f.projectid.touched) }" placeholder="Project ID" name="projectid" formControlName='projectid'>
<button type="button">Validate</button>
<div *ngIf="f.projectid.invalid && (f.projectid.dirty || f.projectid.touched)" class="invalid-feedback">
<div *ngIf="f.projectid.errors.required">Project ID is required</div>
<div *ngIf="f.projectid.errors?.noproject">
Project id is not valid
</div>
</div>
<div *ngIf="f.projectid.errors?.noproject">
Project id is not valid
</div>
{{f.projectid.errors | json}}
</div>
<div class="form-group">
<label for="name">Project Name</label>
<input type="text" class="form-control" id="name" placeholder="Project Name" name="projectname" readonly formControlName='projectname'>
</div>
<div class="form-group d-flex justify-content-end">
<div class="">
<button type="button" class="btn btn-primary">Cancel</button>
<button type="submit" class="btn btn-primary ml-1">Next</button>
</div>
</div>
</form>
Problem is my custom async validation error message is not getting displayed.
Here is stackblitz example
You could do it as follows using rxjs/timer:
import { timer } from "rxjs";
....
return timer(500).pipe(
switchMap(() => {
if (!control.value) {
return of(null);
}
return this._httpService.checkProjectID(control.value).pipe(
map(isTaken => {
console.log(isTaken);
if (isTaken) {
return { noproject: true };
} else {
return null;
}
})
);
})
);
Sample
The real problem is and I have encountered this myself, you subscribe to the value change but you need to wait for the statuschange to return.
It is "PENDING" while it is doing the call.
The debounce/timer/... are just 'hacks' since you never know when the value is returned.
Declare a variable:
this.formValueAndStatusSubscription: Subscription;
In your
this.formValueAndStatusSubscription =
combineLatest([this.form.valueChanges, this.form.statusChanges]).subscribe(
() => this.formStatusBaseOnValueAndStatusChanges = this.form.status
);
Don't forget to desstroy the subscription
The most important point in the async validation is as descriped in Angular Doc
The observable returned must be finite, meaning it must complete at
some point. To convert an infinite observable into a finite one, pipe
the observable through a filtering operator such as first, last, take,
or takeUntil.
so basically you can use for example take(1) , it'll take the first emission then mark the Observable completed
return control.valueChanges.pipe(
debounceTime(500),
take(1),
switchMap(() =>
this._httpService.checkProjectID(control.value).pipe(
map(isTaken =>
isTaken ? { noproject: true } : null
)
))
)
demo
I created a class named alert, and I use it to display alerts whenever new post is created or deleted or changed.
but there is one issue, when I put the setAlert inside a DELETE/POST/PUT function, if the latter is located inside a service component, it gives me an error saying: ERROR
but when I move the function into its component.ts file, it works properly without any issues. So why is that happening and what can I do to make it work in a service?
Here is my Alert.ts:
export class alert{
"status" : boolean;
"text": string;
constructor(){
this.status=false;
this.text="";
}
public setAlert(text){
this.status = true;
this.text = text;
}
public close(){
this.status = false;
}
}
Here is my html file:
<div class="forms container">
<form #postForm="ngForm">
<div class="form-group">
<label for="title">Title</label>
<input [(ngModel)]="formService.form.title"
name="title"
id="title"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea [(ngModel)]="formService.form.body"
name= "body"
id="body"
cols="30"
rows="10"
class="form-control"
></textarea>
</div>
<button class="btn btn-success" (click) = "formService.editForm()">Save</button>
<button class="btn btn-danger pull-right" (click) = "formService.deleteForm()">Delete</button>
<div class="container mt-4">
<div class="row">
<div class="col">
<div *ngIf = "alert.status" class="alert alert-success
alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"
(click) = "alert.close()">
<span aria-hidden="true">×</span>
</button>
{{alert.text}}
</div>
</div>
</div>
</div>
</form>
</div>
Here is component.ts file:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { FormService } from './forms.service';
import { HttpClient } from '#angular/common/http';
import { alert } from './alert';
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
alert: alert;
id: any;
posts: any;
constructor(public formService: FormService ,private route: ActivatedRoute,
private router: Router, private http: HttpClient) { }
ngOnInit() {
this.id=this.route.snapshot.params['id'];
this.alert = new alert();
this.posts = this.formService.getForms(this.id).subscribe(
(forms: any) => {
this.formService.form = forms[0];
}
);
}
}
And here is service.ts file:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { form } from './form-interface';
import { alert } from './alert';
#Injectable({
providedIn: 'root'
})
export class FormService {
formsUrl = "https://jsonplaceholder.typicode.com/posts";
form: form = {
id: 0,
userId: 0,
title: '',
body: ''
};
alert: alert;
constructor(private http: HttpClient) { }
ngOnInit() {
this.alert = new alert();
}
getForms(id) {
return this.http.get('https://jsonplaceholder.typicode.com/posts'
+ "?id=" + id)
}
editForm() {
fetch(this.formsUrl + "/" + this.form.id, {
method: 'PUT',
body: JSON.stringify(this.form),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
this.alert.setAlert("Post has been successfully saved !");
}
deleteForm() {
this.http.delete(this.formsUrl + "/" + this.form.id)
.subscribe(
data => {
console.log("DELETE Request is successful ", data);
this.alert.setAlert("Post has been successfully deleted !");
},
error => {
console.log("Error", error);
}
);
}
}
Services don't have ngOnInit life cycle, change your code from ngOnInit to constructor.
constructor(private http: HttpClient) {
this.alert = new alert();
}
Only components and directives have life cycle hooks:
A Component has a lifecycle managed by Angular itself. Angular creates it, >renders it, creates and renders its children, checks it when its data-bound >properties change and destroy it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, >and destroys them.
I have been trying to hide my form and making it appear only when user click on the button. but for some reason, the function I have created never work is there something wrong with my code? and I saw quite a few example that uses angular.module and I tried it but I always get an error message.
transfer.component.html
<form [formGroup]="AddRiciverForm" id="AddRiciverForm" (ngSubmit)="addRiciverFunc()" *ngIf="show">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p><input type="email" id="emailTo" formControlName="emailTo" placeholder="Reciver Email" [(ngModel)]="this.AddRiciverForm.value.emailTo" required></p>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p><button class="btn btn-primary" type="submit" [disabled]="!transferForm.form.valid">Add</button> </p>
</div>
</div>
</div>
</form>
<button ng-click="AddEmailFunc()">add user</button>
transfer.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '#angular/forms';
import { Router } from '#angular/router';
import { Http } from '#angular/http';
import { PostsService } from '../posts.service';
#Component({
selector: 'app-transfer',
templateUrl: './transfer.component.html',
styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {
constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
transfer = {};
addRiciver = {};
recivers: any;
AddRiciverForm: FormGroup;
transferForm: FormGroup;
public userEmail: string;
show=false;
ngOnInit() {
this.transferForm = this.fb.group({
emailTo: '',
amount: ''
});
this.AddRiciverForm = this.fb.group({
emailTo: ''
});
this.auth.currentEmail.subscribe(email => this.userEmail = email);
this.postsService.getAllReciver().subscribe(reciver => {
this.recivers = reciver;
});
}
transFunds(){
}
addRiciverFunc(){
this.addRiciver={
emailFrom: this.userEmail,
emailTo: this.AddRiciverForm.value.emailTo
}
this.http.post('/transfer', this.addRiciver)
.subscribe(res => {
let id = res['_id'];
}, (err) => {
console.log(err);
}
);
}
AddEmailFunc(){
if(!this.show){
this.show = true;
}
}
}
You must try adding [hidden]="AddEmailFunc()" on your form.
please see my sample code
import { Component } from '#angular/core';
#Component({
selector: 'Sandbox',
template: `<form [hidden]="isDisplayed">
<label>Sample: </label>
<input type="text">
</form>
<button (click)="showMe()">Click</button>`
})
export class SandboxComponent{
isDisplayed = true;
showMe()
{
if(this.isDisplayed)
{
this.isDisplayed = false;
}else{
this.isDisplayed = true;
}
}
}
Hope it helps. :) cheers!
You are mixing angularjs (1.x) and angular (>2)
the ng-click in Angular should be:
<button (click)="AddEmailFunc()">add user</button>
If this does not solve your issue please post the full component.
you can use *ngIf in and (model) binded to event click of button.
<button (click)="changeView()">add user</button>
and clickEvent
changeView(){
this.showForm = !this.showForm;
}