I need to make a traffic light that from 0 to 10 minutes is green from 10 to 20 yellow and from 20 to 30 red, time is by service
So far this is my code
This is the component
import {
Component,
OnInit,
Input
} from '#angular/core';
import {
TiempoService
} from "app/servicios/tiempo.service"
#Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {
#Input() tiemposervice: TiempoService;
constructor() {}
ngOnInit() {
}
}
This is the HTML
<div class="row">
<div class="small-12 medium-6 columns">
<span>Tiempo transcurrido</span>
<h5>{{tiempoTranscurrido | date:'mm:ss'}}</h5>
</div>
</div>
This is the service
import {
Injectable
} from '#angular/core';
import Rx from 'Rx';
#Injectable()
export class TiempoService {
tiempoTranscurrido: number;
constructor() {}
ngOnInit() {
}
tiempoTotal() {
Rx.Observable.interval(1000).subscribe(segundos => {
this.tiempoTranscurrido = segundos * 1000;
})
}
}
I would greatly appreciate your help.
I suggest you need something like this:
Service:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
#Injectable()
export class LightService {
getLight(interval): Observable<string> {
return Observable.interval(interval)
.timeInterval()
.map(time => {
if(time.value % 3 === 2) {
return 'green';
} else if(time.value % 3 === 0) {
return 'yellow';
} else if (time.value % 3 === 1) {
return 'red';
}
});
}
}
Component:
import { Component, OnInit } from '#angular/core';
import { LightService } from './light.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ LightService ]
})
export class AppComponent implements OnInit {
light: string = "green";
constructor(private lightService: LightService) {}
ngOnInit() {
this.lightService
.getLight(10000) // 10 seconds interval
.subscribe(light => this.light = light);
}
}
Template:
<h1>
{{ light }}
</h1>
<ul>
<li *ngIf="light === 'green'" class="green"></li>
<li *ngIf="light === 'yellow'" class="yellow"></li>
<li *ngIf="light === 'red'" class="red"></li>
</ul>
Styles:
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
width: 64px;
height: 64px;
border-radius: 50%;
border: 1px solid black;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.red {
background-color: red;
}
If you need to show lights only once add take operator:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
#Injectable()
export class LightService {
getLight(interval): Observable<string> {
return Observable.interval(interval)
.timeInterval()
.map(time => {
if(time.value % 3 === 2) {
return 'green';
} else if(time.value % 3 === 0) {
return 'yellow';
} else if (time.value % 3 === 1) {
return 'red';
}
})
.take(2);
}
}
Related
HTML
<ion-app>
<ion-content>
<div #scrolledToElement class="second-block" [ngClass]="flag ? 'red' : 'green' "></div>
</ion-content>
</ion-app>
CSS
.second-block {
margin-bottom: 500px;
height: 250px;
width: 100%;
}
.red {
background: red;
}
.green {
background: green;
}
TS
import { Component, VERSION, HostListener, ElementRef, ViewChild } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Ionic 6.2 Angular ' + VERSION.major;
constructor() {}
flag = false;
#ViewChild("scrolledToElement", { static: false })
scrolledToElement: ElementRef;
#HostListener("window:scroll", ["$event"])
onScroll(event) {
if (window.scrollY > this.scrolledToElement.nativeElement.offsetTop) {
this.flag = true;
console.log("flag", this.flag);
}
else
{
this.flag = false;
}
}
}
How to change the class on scroll?
I want a solution for the latest Angular version
stackblitz : https://stackblitz.com/edit/ionic6-angular13-wsjtit?file=src%2Fapp%2Fapp.component.html
Any solution, please?
Working URL :
https://stackblitz.com/edit/angular-ivy-xhb4yw?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.css,src%2Findex.html,src%2Fapp%2Fhello.component.ts,src%2Fapp%2Fapp.module.ts
#HostListener('window:scroll', ['$event']) works fine in the web browser. As you are using ionic you need to use their custom events provided in the documentation for ion-content.
<ion-content [scrollEvents]="true"
(ionScrollStart)="logScrollStart($event)"
(ionScroll)="logScrolling($event)"
(ionScrollEnd)="logScrollEnd($event)">
</ion-content>
Implement above methods in app.component.ts file. You can define your change class logic logScrolling method. Instead of window.scrollY use event.detail.scrollTop from the event provided by ionScroll.
logScrollStart(event) {
console.log("logScrollStart : When Scroll Starts", event);
}
logScrolling(event) {
console.log("logScrolling : When Scrolling", window.scrollY);
console.log("Offset", this.scrolledToElement.nativeElement.offsetTop);
if (event.detail.scrollTop > this.scrolledToElement.nativeElement.offsetTop) {
this.flag = true;
console.log('flag', this.flag);
} else {
this.flag = false;
}
}
logScrollEnd(event) {
console.log("logScrollEnd : When Scroll Ends", event);
}
Here is the forked stackblitz repository.
I am writing, because I have a problem with my resizeable component.
I want have only cursor 'resize' instead of 'not-allowed' on drag.
Could you please for your help?
Component
resizeable.component.ts
import { Component, ContentChild, ElementRef, OnDestroy, ViewChild } from '#angular/core';
import { Subject } from 'rxjs';
#Component({
selector: 'app-resizeable',
templateUrl: './resizeable.component.html',
styleUrls: ['./resizeable.component.scss']
})
export class ResizeableComponent implements OnDestroy {
#ViewChild('line') line: ElementRef;
#ContentChild('content') content: ElementRef;
initHeight: number;
initPositionY: number;
private unsubscribe$: Subject<void> = new Subject<void>();
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
onDrag(event: DragEvent): void {
const height = this.initHeight + (event.clientY - this.initPositionY);
this.content.nativeElement.style.height = `${height}px`;
event.preventDefault();
}
onDragEnd(event: DragEvent): void {
event.preventDefault();
}
onDragStart(event: DragEvent): void {
event.dataTransfer.effectAllowed = 'move';
this.initHeight = this.content.nativeElement.getBoundingClientRect().height;
this.initPositionY = event.clientY;
}
}
resizeable.component.html
<ng-content></ng-content>
<div
#line
*ngIf="content"
(dragend)="onDragEnd($event)"
(dragstart)="onDragStart($event)"
(drag)="onDrag($event)"
class="break-line"
draggable="true"
>
<hr />
</div>
resizeable.component.scss
.break-line {
cursor: row-resize;
height: 0.5rem;
margin-top: 3rem;
width: 100%;
-webkit-user-drag: element;
-webkit-user-select: none;
}
Here I have some static list. I need to change the class on hover and mouseout of the list individually.But here class is getting changed for all list at a time. Here is code below
home.component.html
<div>
<ul>
<li [ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)">test1</li>
<li [ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)">test2</li>
<li [ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)">test3</li>
<li [ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)">test4</li>
</ul>
</div>
home.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
/* First data */
console.log('hello');
}
color:string = 'red';
changeStyle($event){
this.color = $event.type == 'mouseover' ? 'yellow' : 'red';
}
}
css
.yellow{
border-bottom:1px solid;
}
.red{
background:red;
color:#FFF;
}
You can use $event.target.className. It work for current event class. Try the below solution It will work.
changeStyle($event){
$event.target.className= $event.target.className == 'red' ? 'yellow' : 'red';
}
or
changeStyle($event){
$event.target.className = $event.type == 'mouseover' ? 'yellow' : 'red';
}
I need to implement a customized tooltip for ag-Grid in angular 6.
Following is my code :
app.component.ts
import { Component, OnInit } from '#angular/core';
import { MyTooltipComponent } from '../my-tooltip/my-tooltip.component';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
private frameworkComponents = {};
constructor() {
this.frameworkComponents = { myTooltipComponent: MyTooltipComponent };
}
aggridConfig0: any = {
rowData: [],
columnDefs: [],
defaultColDef: {
filter: true,
sortable: true,
resizable: false,
editable: false,
enableRowGroup: false,
tooltipComponent: "myTooltipComponent"
},
cubeXCreateAgGridColumn: (data) => {
let temp = [];
data.forEach((val, key) => {
if (key == 0) {
Object.keys(val).forEach((name) => {
temp.push({
headerName: name,
field: name,
tooltipField: tooltipName
})
})
}
});
return temp;
}
}
private gridApi0;
private gridColumnApi0;
agGrid;
onGridReady0(params) {
this.agGrid = [
{
"header1": "abc",
"header2": "efg"
},
{
"header1": "def",
"header2": "xyz"
}
];
this.gridApi0 = params.api;
this.gridColumnApi0 = params.columnApi;
this.aggridConfig0.rowData = this.agGrid;
this.gridApi0.setColumnDefs(this.aggridConfig0.cubeXCreateAgGridColumn(this.aggridConfig0.rowData));
}
}
app.component.html
<ag-grid-angular class="ag-theme-balham base-padding" style="height: 500px"
[rowData]="aggridConfig0.rowData"
[columnDefs]="aggridConfig0.columnDefs"
[defaultColDef]="aggridConfig0.defaultColDef"
[animateRows]="true"
[suppressDragLeaveHidesColumns]="true"
(gridReady)="onGridReady0($event)"
[frameworkComponents]="frameworkComponents">
</ag-grid-angular>
my-tooltip-component.ts
import {Component, ViewEncapsulation} from '#angular/core';
import {ITooltipAngularComp} from "#ag-grid-community/angular";
#Component({
selector: 'my-tooltip-component',
template: `
<div class="custom-tooltip">
<p><span>Header 1 : {{data.header1}}</span></p>
<p><span>Header 2 : {{data.header2}}</span></p>
</div>`,
styles: [
`
:host {
position: absolute;
width: 150px;
height: 70px;
border: 1px solid cornflowerblue;
overflow: hidden;
pointer-events: none;
transition: opacity 1s;
}
:host.ag-tooltip-hiding {
opacity: 0;
}
.custom-tooltip p {
margin: 5px;
white-space: nowrap;
}
.custom-tooltip p:first-of-type {
font-weight: bold;
}
`
]
})
export class MyTooltipComponent implements ITooltipAngularComp {
private params: any;
private data: any;
agInit(params): void {
this.params = params;
console.log("params here not printing............",params)
this.data = params.api.getDisplayedRowAtIndex(params.rowIndex).data;
this.data.color = this.params.color || 'white';
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { AgGridModule } from 'ag-grid-angular';
import 'ag-grid-enterprise';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing/app-routing.module';
import { MyTooltipComponent } from './component/my-tooltip/my-tooltip.component';
#NgModule({
declarations: [
AppComponent, MyTooltipComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
AgGridModule.withComponents([MyTooltipComponent])
],
providers: [ ],
bootstrap: [AppComponent]
})
export class AppModule { }
Please find the stackblitz url here :
https://stackblitz.com/edit/my-tooltip-app
I am not able to show the customized data from my-tooltip.component.ts to the header1 column tooltip.
I have referred - https://www.ag-grid.com/javascript-grid-tooltip-component/
Please help me out. Thanks in advance
The issue is resolved now.
There was an issue with the AgGrdModule that I imported. Which was previously imported from ag-grid-angular library.
I changed it to #ag-grid-community/angular
In my app.module.ts
import { AgGridModule } from "#ag-grid-community/angular";
Thanks everyone..!!
How do I move my html section from app.compontent.ts to a seperate html documenet? It wont work to just att the html code into the generated class app.component.ts.
Also I would like to move the css section as well to seperate css document.
If someone could help me or point me to the right direction I would be greatfull
import { Component } from '#angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<button> my Button </button>
<h2 pButton type="button" icon="fa-check" iconPos="right">My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span>{{hero.name}}
</li>
</ul>
<hero-detail [hero]="selectedHero"></hero-detail>
`,
styles: [`
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
`],
providers: [HeroService]
})
export class AppComponent implements OnInit{
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService){
}
getHeroes(): void{
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
onSelect(hero: Hero): void{
this.selectedHero = hero;
}
ngOnInit(): void{
this.getHeroes();
}
}
Make use of templateUrl instead of template in Component Decorator
templateUrl - url to an external file containing a template for the
view
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Add all the code to app.component.html
create separate html and css example : home.component.html and home.component.css
in component.ts file add below code
import { Component, OnInit, TemplateRef } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
You can add the html code in a separate html file for example: app.component.html
Copy the template without the inside the app.component.html .
Later in your #Component make the below changes:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
})