How can I route components in another component without changing url? - html

Let's assume that I have Angular 5 project with routings. For instance /home, /landing-page, etc. Moreover, let's assume that in my landing page with url - localhost:4200. I want to create login panel. I have two fields - username and password, one button sign in and two other buttons forgot password? and Don't have an account?. My problem is that when user will click Forgot password? or Don't have an account? he will not be routed to another page with url like localhost:4200/sign-up but he will stay at the same page with url localhost:4200 and fields username, password, sign in, forgot password? and Don't have an account? will disappear and in their place will be displayed fields associated with registration. I am not sure whether you know what I mean. The good example what I wanna to achieve is https://www.instagram.com. No matter whether you click Sign up or Log in you are still on the same url and only one component changes. Do you know how can I achieve this? I am not sure whether I should use routes or maybe another way is more optimal to do this? Thanks in advance.
My code looks in this way. I added only the most important code from selected files.
index.html:
</head>
<body>
<app-root></app-root>
</body>
</html>
app.component.html:
<app-navbar></app-navbar>
<router-outlet></router-outlet>
<app-footer *ngIf="removeFooter()"></app-footer>
At the moment my home.component looks in this way:
home.component.html:
<div *ngIf="isSignIn()">
<app-sign-in></app-sign-in>
</div>
<div *ngIf="isSignUp()">
<app-sign-up></app-sign-up>
</div>
<div *ngIf="isForgotPassword()">
<app-forgot-password></app-forgot-password>
</div>
home.component.ts:
constructor() {
this.signin = true;
this.signup = false;
this.forgot = false;
}
isSignUp() {
if (this.signup === true) {
return true;
}
else {
return false;
}
}
isSignIn() {
if (this.signin === true) {
return true;
}
else {
return false;
}
}
isForgotPassword() {
if (this.forgot === true) {
return true;
}
else {
return false;
}
}
sign-in.component.html:
<div class="content-center">
<div class="container">
<div class="title-brand">
<div align="center">
<input style="background-color: black; border-color: white; color:white; width: 270px" type="text" value="" class="form-control" placeholder="USERNAME">
<br>
<input style="background-color: black; border-color: white; color:white; width: 270px" type="text" value="" class="form-control" placeholder="PASSWORD">
<div class="row">
<div class="col-md-8">
<br>
<button style="background-color: black; border-color: white; color:white; width: 270px" type="button" class="btn btn-danger">Log in</button>
</div>
</div>
<br>
<h6 style = "color: white" [routerLink]="['/main']" skipLocationChange class=pointer>Forgot Password?</h6>
<h6 style="color: white" [routerLink]="['/sign-up']" class=pointer>Don't have an account?</h6>
</div>
</div>
</div>
</div>
UPDATE
I added source code of sign-in.component.html to the question. Can you show me how I can switch the component sign-in.component.html after clicking Forgot Password? or Do not have an account? to the component forgot.component.html or sign-up.component.html

Use skipLocationChange from the route NavigationExtras. E.g.
<h6 style = "color: white" [routerLink]="['/main']" skipLocationChange>Forgot Password?</h6>
<h6 style="color: white" [routerLink]="['/sign-up']" skipLocationChange>Don't have an account?</h6>

Here is an example of using a boolean and buttons to allow you to switch between different components on a single page:
stackblitz example
This example could be improved but I hope it shows you how to easily swap the visible component.
You can view the code at this link
EDIT
You need to remove the responsibility of what component to show to a container component (i.e. a parent component). In the updated stackblitz example I've made the HomeComponent responsible for showing the correct component. This means the SignUp/SignIn/ForgotPassword components have no responsibility for switching between each other - that is the job for the HomeComponent (or whichever component you want to use for that job).
Hope that helps
home.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-home',
template:
`<div *ngIf="signin">
<app-sign-in></app-sign-in>
<button (click)="showSignUp()">Sign up</button>
<button (click)="showForgot()">Forgot password</button>
</div>
<div *ngIf="signup">
<app-sign-up></app-sign-up>
<button (click)="showSignIn()">Sign in</button>
<button (click)="showForgot()">Forgot password</button>
</div>
<div *ngIf="forgot">
<app-forgot-password></app-forgot-password>
<button (click)="showSignUp()">Sign up</button>
<button (click)="showSignIn()">Sign in</button>
</div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HomeComponent {
public signup: boolean = true;
public signin: boolean = false;
public forgot: boolean = false;
constructor() {}
public showSignIn() {
this.signin = true;
this.signup = this.forgot = false;
}
public showSignUp() {
this.signup = true;
this.signin = this.forgot = false;
}
public showForgot() {
this.forgot = true;
this.signin = this.signup = false;
}
}

Related

How to make new line input message by pressing shift + enter? Angular

I have a chat box with a single input field. I want to make handle new line input like Facebook's chatbox.
My Chat Box:
[1]: https://i.stack.imgur.com/NeG7d.png
My HTML of input field:
<form class="form" #msgForm="ngForm" (ngSubmit)="send(msgForm)" focus>
<div class="form-group">
<div class="col-xs-5">
<div class="input-group">
<input type="search" autocomplete="off" class="form-control left-border-none"
name="message" [(ngModel)]="message" placeholder="Say Something..."
(input)="onChange($event.target.value)" />
<span class="input-group-addon transparent">
<button type="submit" (keyup.enter)="send(msgForm)"
style="border: 0; background: none;cursor: pointer;"><i class="fa fa-paper-plane" [hidden]="isHidden"
style="font-size:20px;color: #6d5cae;"></i></button>
</span>
</div>
</div>
</div>
</form>
Here's my solution.
Brief Note It's not the exact answer because I had the same problem and after a lot of testing, found more adequate to let "Enter" for newlines and"Shift+Enter" for sending messages
This is the opposite logic of popular apps like WS and MSg but I found
more suitable for people having a conversations over a web based chat, since in a conversation you want sometimes to write long messages, and for people habituated to type on text editors, this is the logic function of pushing "Enter".
People may disagree, but just hope you can find it useful
What I did was to using a text-area as container, for easier auto-sizing and multi-line configuration
After that, I created a button that posts the message once clicked,and a #Hostlistener for the event to bind the button to the method.
Please refer to the code.
Best regards
HTML from the typing bar component
<!-- (keydown)="onKey($event)" -->
<!-- submit message with enter -->
<!-- (keydown.enter)="postMessage(messageContainer)" -->
<!-- (keyup.enter)="onKeydown($event)" // for event methods -->
<div class="typing-bar prim-color" >
<textarea
matInput
matAutosize
name=""
cdkTextareaAutosize
#messageContainer
#autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="2"
cdkAutosizeMaxRows="7"
>
</textarea>
<button
mat-stroked-button
color="accent"
(click)="postMessage(messageContainer)"
[disabled]="messageContainer.value===''"
><mat-icon>send</mat-icon> Send</button>
</div>
TS Code for the component
import { Component, HostListener, OnInit } from '#angular/core';
#Component({
selector: 'app-typing-bar',
templateUrl: './typing-bar.component.html',
styleUrls: ['./typing-bar.component.scss']
})
export class TypingBarComponent implements OnInit {
displayBar: boolean = true;
constructor() { }
ngOnInit(): void {
}
#HostListener('body:keydown.shift.enter',['$event'])launchPost($event: KeyboardEvent): void{
return this.postMessage($event.target as HTMLTextAreaElement)
}
postMessage(textarea:HTMLTextAreaElement){
//post message here
// ....logic...
//reset textarea
textarea.value = ""
//give focus back
textarea.focus();
//debug: this is for test only. Delete after testing
alert('sent')
}
}
SCSS code for the component (maybe not the final version)
.typing-bar{
display: flex;
justify-content: space-around;
padding: 3px;
padding-right: 10px;
margin: 1px;
position: sticky;
bottom: 0;
}
textarea {
overflow: auto;
width: 93%;
// max-height: 20%;
border-radius: 10px;
font-size: 1.3em;
font-family: Arial, Helvetica, sans-serif;
}
// .typing-bar button{
// }

Toggle menu with jQuery

I have been racking my brain how I could include a toggle menu on my website, after some searching I found the below and have implemented it, which is great!
http://jsfiddle.net/hhcsz5cr/
<div>
<h1><button class="button" data-circle="travel">
<i class="fa fa-plus-square"></i>
</button> Travel</h1>
</div>
<div class="travel options">
<ul>
<li>Travel</li>
<li>Vehicles</li>
</ul>
</div>
var localStorageKey = "app_state";
// to preserve state, you first need to keep track of it
var default_state = {
biographies: false,
pictures: false,
poetry: false
}
var saved_state = localStorage.getItem(localStorageKey);
// ternary operator which means if `saved_state` is true we parse it and use that value for `state`; otherwise use `default_state`
var state = saved_state ? JSON.parse(saved_state) : default_state;
$(function() {
init();
$('.button').on('click', function() {
var circle = $(this).attr('data-circle');
toggleCircle(circle, !state[circle]);
$(this).find('i').toggleClass('fa-minus fa-plus');
});
});
function init() {
for(var key in state) {
var is_displayed = state[key];
if ( is_displayed ) {
$(this).find('i').toggleClass('fa-minus fa-plus');
} else {
$(this).find('i').toggleClass('fa-plus fa-plus');
}
console.log(is_displayed);
toggleCircle(key, is_displayed);
}
}
function toggleCircle(circle, is_displayed) {
if (is_displayed) {
$('.'+circle).show()
state[circle] = true;
} else {
$('.'+circle).hide()
state[circle] = false;
}
localStorage.setItem(localStorageKey, JSON.stringify(state));
}
But.. if you minimize a menu then refresh the icon shows a - even though its already minimize.
Is there any way I can change this?
I realise the code above is not my own and I can't find the person to credit! My jquery is terrible.
Any help would be appreicated.
Thanks
jsFiddle DEMO (since SO snippets do not allow localStorage from Iframe)
Use IDs, not classes. IDs are unique, not classes.
Store the entire ID as the object property i.e: "#pictures": false,
Store the entire selector inside data-* i.e: data-toggle="#biographies"
Use "is-*" classes as state CSS helpers: "is-hidden", "is-expanded"
You don't have to use .fa classes, just use CSS and font-family
Make use of Object.assign() to override your default values with the ones in Local Storage (if any).
Loop your object key value pairs using Object.entries() when initing your menu states.
// Override defaults with localStorage
const state = Object.assign({
"#biographies": false, // Feel free to change this default boolean
"#pictures": false,
"#poetry": false
}, JSON.parse(localStorage.state || "{}"));
const toggle = (k, v) => {
$(k).toggleClass('is-hidden', !v);
$(`[data-toggle="${k}"]`).toggleClass('is-expanded', v);
};
// On init
Object.entries(state).forEach(([k, v]) => toggle(k, v));
// On click
$("[data-toggle]").on("click", function() {
const id = this.dataset.toggle; // Get ID i.e: "#pictures"
state[id] = !state[id]; // Flip boolean
toggle(id, state[id]); // Trigger UI changes
localStorage.state = JSON.stringify(state); // Store into LS
});
.is-hidden {
display: none;
}
[data-toggle] i:before{
font-family: "FontAwesome";
font-style: normal;
content: "\f067"; /* Plus */
}
[data-toggle].is-expanded i:before{
content: "\f068"; /* Minus */
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<div id="biographies" class="is-hidden">Biography</div>
<div id="pictures" class="is-hidden">Pictures</div>
<div id="poetry" class="is-hidden">Poetry</div>
<button type="button" class="button" data-toggle="#biographies">
<i></i> biographies
</button>
<button type="button" class="button" data-toggle="#pictures">
<i></i> pictures
</button>
<button type="button" class="button" data-toggle="#poetry">
<i></i> poetry
</button>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Please try this..
$('.button').click(function(){
var whichbtn = $(this).attr('data-circle');
if($("."+whichbtn).hasClass("hidden")){
$(this).children("i").removeClass("fa-plus").addClass("fa-minus");
}else{
$(this).children("i").addClass("fa-plus").removeClass("fa-minus");
}
$("."+whichbtn).toggleClass("hidden");
});
.hidden{display:none;}
.button{
background:#00cc00;
padding:10px 20px;
margin-right:10px;
border:none;
color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="m-3">
<div class="biographies hidden mb-2 font-weight-bold">Biography</div>
<div class="pictures hidden mb-2 font-weight-bold">Pictures</div>
<div class="poetry hidden mb-2 font-weight-bold">Poetry</div>
<button class="button" data-circle="biographies">
<i class="fa fa-plus"></i> biographies
</button>
<button class="button" data-circle="pictures">
<i class="fa fa-plus"></i> pictures
</button>
<button class="button" data-circle="poetry">
<i class="fa fa-plus"></i> poetry
</button>
</div>
I add js for click event of button and get the attribute of data-circle of it's own for find which button clicked. And fa fa-plus icon changed to fa fa-minus also. Thats only.
toggleClass is used for toggle class when user click the button. First click add class hidden then second click remove class hidden.For more clarifications comment me.

Hide overlaypanel when I click outside the box or in the box Angular 4

I have created an OverlayPanel like component so there I can put more clicks or something else.
But when I click outside the overlay or in the overlay this does not exit stays always there, it is dissapear only when I click in button what I have writed.
Here is the link of the StackBlitz
I have like this the overlaPanel created.
<div class="dropdown">
<div (click)="toggle()" class="body">
<ng-content select="[body]"></ng-content>
</div>
<div *ngIf="active" class="popup" >
<ng-content select="[popup]"></ng-content>
</div>
</div>
.dropdown {
position: relative;
display: inline-block;
}
.popup {
display: block;
position: absolute;
z-index: 1000;
}
export class OverlaypanelComponent implements OnInit {
active = false;
constructor() {
}
offClickHandler(event: any) {
if (event['.body'] && event['.popup'] === true) {
this.active = false;
}
}
ngOnInit(): void {
}
toggle() {
this.active = !this.active;
}
close() {
this.active = !this.active;
}
}
And this is when I call this component
<app-overlaypanel>
<div body [ngClass]="[getBackgroundColorClass(),clazz]" class="fa fa-pencil-square-o edit-block"></div>
<div class="overlayPopup" popup>
<div class="dropdown-menu-item" (click)="openTechnicalEditDialog({cluster: cluster, type: clazz})">Edit</div>
<div class="dropdown-menu-item" (click)="delete()">Delete</div>
<div class="dropdown-menu-item" (click)="openTechnicalEditDialog({appendToParentId: cluster.id})" *ngIf="cluster.level <= 9">Append</div>
<div
class="dropdown-menu-item" (click)="clicked.emit()">Assign</div>
</div>
</app-overlaypanel>
If you want to close the drop down when you click outside of your menu you can use host listener to know whether you clicked outside or not
#HostListener('document:click', ['$event']) clickedOutside($event){
this.active=false;
}
I have attached the example check this out: https://stackblitz.com/edit/angular-5p5d1b
You can use ng-click-outside module as described here https://www.npmjs.com/package/ng-click-outside
working with me fine in angular 8
I know the question says Angular 4 but incase if someone is wondering how can we do the same with latest version of angular.
Now Anglar Material overlay comes with such directive and event listener.
<ng-template
cdkConnectedOverlay
[cdkConnectedOverlayOrigin]="trigger"
[cdkConnectedOverlayOpen]="isOpen"
[cdkConnectedOverlayHasBackdrop]="isOpen"
[cdkConnectedOverlayBackdropClass]="'cdk-overlay-transparent-backdrop-cs'"
(backdropClick)="isOpen = !isOpen"
>
content to be shown on overlay
</ng-template>

Angular 2 show and hide scroll button

I have a button that shows up on the right corner when I make the first scroll down move. I want to make my button disappear after I scroll up on the page.
How can I do this?
So far, my typescript function track($event:any){} looks like this:
import { Component } from '#angular/core';
#Component({
host: {'(window:scroll)': 'track($event)'}
})
export class DirectSearchComponent{
showScrollButton:boolean=false;
beginY: any;
constructor() {}
track($event:any) {
console.debug("Scroll Event", $event);
if (this.beginY == undefined || this.beginY != null) {
if (this.beginY > $event.scrollY) {
this.showScrollButton = false;
}
else {
this.showScrollButton = true;
}
}
else {
this.beginY = $event.scrollY;
this.showScrollButton = true;
}
}
}
And my html code for the button looks like this:
<a href="#" class="scrollup">
<button *ngIf="showScrollButton"
type="button" class="btn btn-primary btn-block pull-right"
style="position: fixed; bottom: 10px; right: 51px;
width:3%; overflow:auto;">
<i class="glyphicon glyphicon-chevron-up" ></i>
</button>
</a>
Thanks in advance!
Looks like this.beginY is not being initialized properly.
Import NgOnInit and in the NgOnInit method, set...
this.beginY = document.documentElement.scrollTop || document.body.scrollTop;
This should properly initialize your variable to the initial page scroll value.

cannot set value for controls on reactjs bootstrap html tooltip

I am trying to get something like x-editable inline edit in reactjs. I am able to get the HTML form/control inside the bootstrap tooltip, however, not able to set or change value on the input control on the popover. Below is the code.
class Inline extends React.Component {
constructor(props, context) {
super(props, context);
this.state= {
displayText: props.displayText,
valueText : props.valueText
}
}
componentDidMount() {
$("[data-toggle=popover]").popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
$(document).on("click", ".popover .close" , function(){
$(this).parents(".popover").popover('hide');
});
}
onChange(e) {
console.log('on change : ' + e.target.value)
this.setState({ displayText: e.target.value });
}
handleClick (e) {
e.preventDefault();
console.log('The link was clicked.');
}
render(){
return (
<div className="container">
<ul className="list-unstyled inline-edit">
<li><a data-placement="bottom" data-toggle="popover" data-title="Inline Edit <a href='#' class='close' data-dismiss='alert'>×</a>" data-container="body" type="button" data-html="true" href="#" >{this.state.displayText}</a></li>
<div id="popover-content" className="hide">
<div className="form-group">
<span>{this.state.displayText}</span>
<input type="text" placeholder="Name" className="form-control"
value={this.state.displayText}
onChange={this.onChange}
></input>
<div className="form-group edit-control">
<a href="#" role="button" onClick={this.handleClick}><i className="fa fa-check-circle fa-2x green"/></a>
<a href="#" role="button" ><i className="fa fa-times-circle fa-2x red leftpad"/></a>
</div>
</div>
</div>
</ul>
</div>
);
}
};
Inline.propTypes = {
displayText: PropTypes.string.isRequired,
valueText: PropTypes.string.isRequired
};
export default Inline;
Screen shot
The issue is in the way your popover is created:
componentDidMount() {
$("[data-toggle=popover]").popover({
html: true,
content: function () {
return $('#popover-content').html();
}
});
}
You are using jquery html() function to duplicate a Html DOM element in the bootstrap popover. When duplicating an html element this way, the JavaScript React logic is not attached to the duplicated html code.
You can't only use the bootstrap tool tip to created the popover. You have to:
Either manually instantiate a react component in the popover (using the ReactDom render function).
Or (the better solution I think) use the dedicated react bootstrap lib that provide the popover bootstrapreact component