How to close Material Dialog after click a button - javascript

This is the code of my dialog :
<ul class="list-group">
<li class="list-group-item" *ngFor="let area of data.arregloAreas[data.index].listo">
<button class="btn btn-primary" [routerLink]="['/vertrabajadores', area]"><span class="fa fa-arrow-right"></span> </button> {{area | titlecase}}
</li>
<li class="list-group-item" style="color: red;" *ngIf="data.arregloAreas[data.index].listo.length == 0">
No existen áreas completas
</li>
</ul>
Everything works fine, I can navigate without problem. But when it changes the page, the dialog persists over the page, so I have to click outside in order to close it. My idea is when I click the button that contains the routerLink, close the dialog immediately.
I think I can put a (click) method in the navigate button but I don't know any method to close the dialog.
EDIT: code of dialog.ts
import { Component, OnInit, Inject } from '#angular/core';
import {MAT_DIALOG_DATA} from '#angular/material/dialog';
#Component({
selector: 'app-dashboarddialog',
templateUrl: './dashboarddialog.component.html',
styleUrls: ['./dashboarddialog.component.css']
})
export class DashboarddialogComponent implements OnInit {
constructor(#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(data.arregloAreas)
}
ngOnInit(): void {
}
}

import { Component, OnInit, Inject } from '#angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '#angular/material/dialog';
#Component({
selector: 'app-dashboarddialog',
templateUrl: './dashboarddialog.component.html',
styleUrls: ['./dashboarddialog.component.css']
})
export class DashboarddialogComponent implements OnInit {
constructor(
private dialogRef: MatDialogRef,
#Inject(MAT_DIALOG_DATA) public data: any
) {
console.log(data.arregloAreas)
}
ngOnInit(): void {
}
closeModal() {
this.dialogRef.close();
}
}
<button class="btn btn-primary" (click)="closeModal()" [routerLink]="['/vertrabajadores', area]"><span class="fa fa-arrow-right"></span> </button>

Related

Change login button to logout in angular 13

I have a simple list with two buttons. I want to be able to show one or the other depending on whether I'm logged in.
<div>
<li class="nav-item">
<button *ngIf="token === ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="login()">Inicia sesión</button>
<button *ngIf="token != ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="logout()">Cerrar sesión</button>
</li>
</div>
I tried simply putting the ngIf but it doesn't make it instant, besides that since the log in is in another component I don't really know how to change that from there.
this is my component:
import { Component, ElementRef, ViewChild} from '#angular/core';
import { Router } from '#angular/router';
import { faHamburger } from '#fortawesome/free-solid-svg-icons';
import { UsersService } from './services/user.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-app';
token = this.userService.getToken();
#ViewChild('clickLogout')clickLogout:ElementRef;
faHamburger = faHamburger;
constructor(public userService: UsersService, public router: Router) { }
logout(){
this.userService.logout();
this.router.navigateByUrl('/login');
}
login(){
this.router.navigateByUrl('/login');
}
}
So as it is, I would need to reload the page every time I need one button or another and I need it to do it instantly when I log in or log out.
try to use that in html,
<div *ngIf="token === ''; else empty">
<button type="button" class="btn btn-dark btn-lg fs-4"
(click)="login()">Inicia
sesión</button>
</div>
<ng-template #empty>
<button type="button" class="btn btn-dark btn-lg fs-4"
(click)="logout()">Cerrar sesión</button>
</ng-template>
in ts call the token in the ngOnInit method and change the route (/login to /logout when you navigate) :
export class AppComponent implements OnInit {
//code...
token=''
ngOnInit(): void {
this.token = this.userService.getToken();}
You should use BehaviorSubject to store the token in the service, add:
public token$ = new BehaviorSubject<string>(null);
then use this.token$.next(valueFromRequest); when you will receive token value and
this.token$.next(null); to reset it.
In html code use ngIf in that way:
<button *ngIf="(userService.token$ | async)" type="button" [...]>Logout</button>
<button *ngIf="!(userService.token$ | async)" type="button"[...]>Login</button>

Need dynamically created buttons to work independently in Angular

In Angular i have dynamically created a group of buttons that all have the same action (to show text when clicked) everything works fine yet when I click one button they all perform the action. I need them to work independently of each other. I have dynamically made a different id for each button and was wondering if there was a way to us the id to have them work independently.
Button HTML and TS files:
<button id="{{index}}" class="btn btn-secondary" style="float: right;" (click)="onClick()">Discription</button>
import { Component, EventEmitter, OnInit, Output, Input } from '#angular/core';
#Component({
selector: 'app-discription-btn',
templateUrl: './discription-btn.component.html',
styleUrls: ['./discription-btn.component.css']
})
export class DiscriptionBtnComponent implements OnInit {
#Output() btnClick = new EventEmitter();
#Input() index!: number
constructor() { }
ngOnInit(): void { }
onClick() {
this.btnClick.emit();
}
}
Button Parent HTML and TS files:
<div class="card mb-4 h-100">
<img class="card-img-top-other" src= "{{ post.link }}" />
<div class="card-body">
<div class="small text-muted"> {{ post.created }} <app-discription-btn (btnClick) = "toggleDiscription()" [index] = index></app-discription-btn> </div>
<h2 class="card-title h4"> {{ post.title }} </h2>
<div *ngIf="showDiscription">
<p class="card-text"> {{ post.summary }} </p>
<a class="btn btn-primary" href="#!">Read More -></a>
</div>
</div>
</div>
import { Component, OnInit, Input } from '#angular/core';
import { Subscription } from 'rxjs';
import { BlogPost } from 'src/app/Post';
import { DiscriptionUiService } from 'src/app/services/discription-ui.service';
#Component({
selector: 'app-other-posts',
templateUrl: './other-posts.component.html',
styleUrls: ['./other-posts.component.css']
})
export class OtherPostsComponent implements OnInit {
#Input() post! : BlogPost
#Input() index! : number;
showDiscription : boolean = false;
subscription : Subscription;
constructor(private discritpionService: DiscriptionUiService) {
this.subscription = this.discritpionService.onToggle().subscribe((value) => (this.showDiscription = value));
}
ngOnInit(): void {
}
toggleDiscription(){
this.discritpionService.toggleDiscription();
}
}
Main HTML and TS files:
<div class="container">
<div class="row">
<div class="col-lg-8"><app-featured-post *ngFor="let post of posts; let i = index;" [post] = "post" [index] = "i"></app-featured-post></div>
<div class="col-lg-4"><app-side-widgets></app-side-widgets></div>
<app-other-posts *ngFor="let post of posts | myFilterPipe:filterargs; let i = index;" [post] = "post" [index] = "i" class="col-lg-4" style="padding-top: 10px;" ></app-other-posts>
<nav aria-label="Pagination">
<hr class="my-0" />
<ul class="pagination justify-content-center my-4">
<li class="page-item disabled"><a class="page-link" href="#" tabindex="-1" aria-disabled="true">Newer</a></li>
<li class="page-item active" aria-current="page"><a class="page-link" href="#!">1</a></li>
<li class="page-item"><a class="page-link" href="#!">Older</a></li>
</ul>
</nav>
</div>
</div>
import { Component, OnInit } from '#angular/core';
import { BlogPostService } from 'src/app/services/blog-post.service';
import { BlogPost } from '../../Post';
#Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
filterargs = {title: 'The Beginning'}
posts: BlogPost[] = [];
constructor(private postService: BlogPostService ) { }
ngOnInit(): void {
this.postService.getPosts().subscribe((posts) => (this.posts = posts));
}
}
Any ideas would be a great help. Thank you ahead of time!

ng-select - when dropdown is opened it is scrolled far-down by default

I am using ng-select for dropdown list (multiselect).
ng-select has native problem so when all items are auto-selected on dropdown init, it will be auto-scrolled far-down to last item.
It is working when no items are preselected on init but I need them all to be preselected on init.
Is there a chance to avoid this behavior?
Could this approach work?
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'myForm',
templateUrl: './myForm.component.html',
styleUrls: ['./myForm.component.scss']
})
export class AlarmComponent implements OnInit {
myForm: FormGroup;
dropdownitems: [];
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {this.initializeForm();}
initializeForm() {this.myForm = this.formBuilder.group({myDropdown: [''] });
html-file
<div class="card text-center>
<form [formGroup]=" myForm" (ngSubmit)="onSubmit()" class="col-xl-12">
<ng-select [items]= dropdownitems" formControlName="alarm" > </ng-select>
<!-- bindValue="" bindLabel="" (change)="onChanged($event)"are optional -->
<button class="btn btn-primary" type="submit">submit</button>
</form>
</div>
If this doesn't fit your needs, please add the html- and the ts-template (complete) to your question. Or a link to somewhere where they can be found.
Take care and good luck.

Angular2 add HTML to dynamic elements

I have this code:
import { Component, ElementRef, Renderer2 } from '#angular/core';
#Component({
selector: 'my-app',
template: '<button (click)="runR()">Run</button>
<div class="testme">
<div class="somediv">
<div class="dynamically_created_div unique_identifier"></div>
<div class="dynamically_created_div unique_identifier"></div>
<div class="dynamically_created_div unique_identifier"></div>
</div>
</div>',
})
export class AppComponent{
hostEl: any;
constructor(
private el:ElementRef,
private renderer:Renderer2,
) {
this.hostEl = el.nativeElement;
}
runR(){
let change_this;
change_this= this.renderer.createElement('span');
this.renderer.addClass(change_this, 'change_this');
this.renderer.appendChild(this.hostEl, change_this);
}
}
Is there any way in Angular2 to add HTML to the .dynamically_created_div?
Because the above only adds to the end of the HTML of the component.
I also tried with:
import { Component, ElementRef, ViewChild, Renderer, AfterViewInit } from '#angular/core';
#Component({
selector: 'my-app',
template: `<button (click)="runR()">Run</button>
<div class="testme">
<div class="somediv">
<div class="dynamically_created_div">
</div>
</div>
</div>
`,
})
export class AppComponent {
constructor(private renderer:Renderer) {}
runR() {
#ViewChild('dynamically_created_div') d1:ElementRef;
this.renderer.invokeElementMethod(this.d1.nativeElement, 'insertAdjacentHTML', ['beforeend', '<div class="new_div">new_div</div>'] );
}
}
But it's not working because the #ViewChild directive must be outside the function and I can't have control over it anymore
I also tried like this:
<div class="dynamically_created_div" [innerHtml]="newHTML"></div>
this.newHTML = '<div class="new_div">new_div</div>';
Thing I cannot do because my content is dynamic and uses unique IDs and I cannot use [innerHtml] dynamically ( it only works for what I put in themplate for the first time, then anything else that changes can't use innerHtml anymore.
I checked Angular2: Insert a dynamic component as child of a container in the DOM but there is the same problem, the placeholders aren't dynamic
UPDATE:
My code is a little bit more complex:
TS:
import { AfterContentInit, Component, OnInit, OnDestroy, ViewEncapsulation } from '#angular/core';
import { NgForm, FormsModule, ReactiveFormsModule, FormGroup, FormControl, FormBuilder, Validators } from '#angular/forms';
import { SFService } from '../services/sf.service';
import { Injectable, Pipe, PipeTransform } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
providers: [ SFService ],
})
export class AppComponent implements OnInit {
constructor(
private sfservice: SFService,
) {}
ngOnInit(){
this.sfservice.getMembers().subscribe(members => {
this.members = members.members;
});
}
members: Member[];
member_selector: Member[];
member_each: Member;
member_selector_each: Member[];
cases: Case;
runR(){
this.members.forEach(member_each => {
this.member_selector.forEach(member_selector_each => {
if(member_each.Id === member_selector_each.Id){
console.log(member_selector_each.Id);
this.sfservice.getCaseHistory(member_selector_each.Id, "2017-04-25T00:00:00", "2017-04-28T23:59:59").subscribe(cases => {
this.member_each['cases'] = cases;
console.log(this.member_each);
});
}
})
})
}
}
HTML:
<form #myForm="ngForm" novalidate>
<select name="member_selector_name" [(ngModel)]="member_selector" multiple ng-model="selectedValues" style="height:200px;">
<option *ngFor="let member of members" [ngValue]="member">{{member.Name}}</option>
</select>
<button (click)="runR()">Run</button>
</form>
<div id="results">
<div *ngFor="let mem of members" class="member-card-{{mem.Id}}">
<div class="card-container">
<div *ngFor="let case of mem.Cases" class="case-card" id="{{case.Id}}">{{case.Number}}
</div>
</div>
</div>
</div>
I was trying to use only ngFor but now I get
Cannot set property 'cases' of undefined
What's the problem with this approach?
export class AppComponent{
#ViewChild('d1') d1:ElementRef;
#ViewChild('d2') d2:ElementRef;
#ViewChild('d3') d3:ElementRef;
constructor(private renderer:Renderer2) { }
runR(){
let change_this;
change_this= this.renderer.createElement('span');
this.renderer.addClass(change_this, 'change_this');
this.renderer.appendChild(this.d1, change_this);
}
}
Template:
<div class="dynamically_created_div unique_identifier" #d1></div>
<div class="dynamically_created_div unique_identifier" #d2></div>
<div class="dynamically_created_div unique_identifier" #d3></div>
you can use ngfor and create you elements inside it and using index you can create different ids and names.
I do something like this i dont know if you want to do the same but here's my code to create some input's dynamically and add or access their values
<div *ngFor="let comp of templateVals | async;let i=index">
<md-input-container class="example-90" *ngIf="comp.type=='code'">
<textarea rows="4" mdInput name="desc{{i}}" [(ngModel)]="comp.data" placeholder="Description"></textarea>
</md-input-container>
<md-input-container class="example-90" *ngIf="comp.type=='text'">
<textarea rows="4" mdInput name="text{{i}}" [(ngModel)]="comp.data" placeholder="Text"></textarea>
</md-input-container>
<md-input-container class="example-90" *ngIf="comp.type=='title'">
<input mdInput name="title{{i}}" [(ngModel)]="comp.data" placeholder="Title">
</md-input-container>
<span class="example-90" *ngIf="comp.type=='upload'">
<input-file *ngIf="!comp.data" [acceptId]="comp.id" (onFileSelect)="addedFileInfo($event)"></input-file>
<span *ngIf="comp.data">{{comp.data}}</span>
</span>
<span class="example-10">
<button md-mini-fab (click)="removeThis(comp)"><md-icon>remove circle</md-icon></button>
</span>
</div>

Angular 2 scope of Dynamic component

I have been learning about Angular 2 and their new features and i am having trouble when adding a component dynamically.
so i have a dashboard.component.ts
import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver, ViewChild } from '#angular/core';
import { InputTextComponent } from '../input-text/input-text.component'
#Component({
templateUrl: 'dashboard.component.html',
providers: [InputTextComponent],
styleUrls: ['dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor( private componentFactoryResolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef,
private inputTextComponent: InputTextComponent
) { }
#ViewChild(InputTextComponent) textComponent: InputTextComponent
attachIntup(){
const factory = this.componentFactoryResolver.resolveComponentFactory(InputTextComponent);
const ref = this.viewContainerRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
alertPop(){
alert(this.textComponent.passingStr);
}
ngOnInit() {
}
}
and it has an html code dashboard.component.html
<button (click)="attachIntup()">Inject Input</button>
<button (click)="alertPop()">Pop String</button>
and my inputTextComponent is as follows
import { Component, AfterViewInit } from '#angular/core';
#Component({
selector: 'app-input-text',
templateUrl: './input-text.component.html',
styleUrls: ['./input-text.component.css']
})
export class InputTextComponent implements AfterViewInit {
public inputType = '';
public passingStr = '';
constructor() { }
popupAlert(){
alert(this.passingStr);
}
ngAfterViewInit() {
this.inputType = 'text'
}
}
with an html:
<div [ngSwitch]="inputType" class="container">
<div class="row" *ngSwitchCase="'textarea'">
<div class="col-md-4">
<label>I am a textarea: </label>
</div>
<div class="col-md-8">
<textarea style="resize: both" class="form-control"></textarea>
</div>
</div>
<div class="row" *ngSwitchCase="'text'">
<div class="col-md-4">
<button (click)="popupAlert()"></button>
<label>I am an input text: </label>
</div>
<div class="col-md-8">
<input type="text" class="form-control" placeholder="Testing text" [(ngModel)]="passingStr">
</div>
</div>
</div>
What i am trying to do is obtain the scope from the inputTextComponent inside the dashboard component. I have read that the ViewChild allows you to access the variables inside a component, but in my case i am not able to do so.
Does anyone know how i can access the variables inside the InputTextComponent after injection; In order to display in the alert from the dashboard whatever information is been passed through the input.
Thanks in advance

Categories

Resources