in dynamic div - on click highlight color - html

HTML
<div class="nav--small nodeLevel newColor" id="rowItem-{{i}}" *ngFor="let root of rootzTemplates; let i=index" (click)="nodeClickLevel1(root,i)">
<p style="padding: 19px 1px;color: #fff; text-align: center;">
{{root}}
</p>
</div>
CSS
.activeColor {
background-color: grey;
}
JavaScript
constructor(private el: ElementRef) { }
nodeClickLevel1(root, id){
this.myTag = this.el.nativeElement.querySelector("#rowItem-" + id);
this.myTag.classList.remove('activeColor');
this.myTag.classList.add('activeColor');
}
Now div is dynamic, say number of div element is 6, on click event i have to change particular clicked div background-color to grey and rest of color should remain same.
Now if I click on div say 2, only 2nd div has highlight with grey color, rest of the color should remain same and vice versa.

Change your function like this
nodeClickLevel1(root, id){
this.myTag = root
}
change your template code like this
[class.newColor]="root === myTag"
Hope it will solve your problem.

Your code can be much simpler, no need for troublesome ElementRef, no need for index ids, etc.
So here is the code:
//our root app component
import { Component, NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
#Component({
selector: 'my-app',
// templateUrl: "app.html",
template: `
<div class="nav--small nodeLevel newColor" [class.activeColor]="root === myTag" *ngFor="let root of rootzTemplates" (click)="nodeClickLevel1(root)">
<p style="padding: 19px 1px;color: #fff; text-align: center;">{{root}}</p>
</div>
`,
})
export class App {
name: string;
constructor() { }
protected myTag:any;
public rootzTemplates: any[] = ["first", "2nd", "3rd"];
nodeClickLevel1(root){
this.myTag = root;
}
}
#NgModule({
imports: [BrowserModule],
declarations: [App],
bootstrap: [App],
})
export class AppModule {}
and css:
.activeColor {
background-color: grey !important;
}
.nav--small{
background-color: black;
}
Here is the working PLNKR link:
http://plnkr.co/edit/oRZa3E5WtYpusKHd

Related

On scroll change class Angular

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.

How to change this template driven form to Reactive form in Angular?

How to change this template driven form to Reactive form? I want to change this template driven form to reactive form. What changes shall I do to change it to Reactive form? The code is complete no other modification is required? Can someone please help me with this, I am attaching all the required codes. What things we should keep in mind while changing to reactive form, also why reactive form is preferred over template driven form?
HTML code
<html>
<body>
<nav>
<div class = "navbar-header">
Image Change on clicking Enter in TextBox
<input class = "col" type = "text" readonly value ="{{imgNumber}}/3 {{cityImageId}}">
</div>
</nav>
<div class = "textarea" contenteditable #scrollDiv [scrollTop]="scrollDiv.scrollHeight" wrap="hard">
<img contenteditable="false" [src]="imagePath" width = "1090px" height = "440"/>
</div>
<form>
<div>
<input type = "text" class="col2" [(ngModel)]="pincode" (keyup.enter)="generatecityDetailArray()" maxlength="6" [ngModelOptions]="{standalone: true}"/>
</div>
</form>
<div>
<input type = "label" class = "col3" value = "Pin Code" readonly />
</div>
</body>
</html>
CSS code
nav {
background-color:black;
border : 0;
}
.navbar-header{
text-align: center;
}
.navbar-header{
color:white;
}
.col{
margin-left: 950px;
text-align: right;
border : 0;
background-color:rgb(160,0,0);
}
.textarea{
overflow: scroll;
height: 400px;
width:1090px;
background-color:white;
margin-left: 100px;
margin-top: 50px;
object-fit: none;
object-position: 1000px 200px;
}
.col2{
width:230px;
height: 30px;
margin-top: 20px;
margin-left: 950px;
}
.col3{
width:230px;
height: 30px;
margin-top: 20px;
margin-left: 950px;
}
TypeScript Code
import { Component, OnInit } from '#angular/core';
import { CityClassificationService } from 'src/app/service/city-classification.service';
#Component({
selector: 'app-city-classification',
templateUrl: './city-classification.component.html',
styleUrls: ['./city-classification.component.css']
})
export class CityClassificationComponent implements OnInit {
imgNumber : number =-1;
cityImageId : number = -1;
imagePath : string ='';
pincode:string='';
curImageNumber:number=0;
imageDetails:{imageName:string,cityImageId:number,imgNumber:number}[]=[];
cityDetailArray :{ pincode : string; cityImageId : number; imgNumber:number;}[] = [];
constructor(private cityService:CityClassificationService) { }
ngOnInit(): void {
this.imageDetails=this.cityService.getImageObject();
this.getNextImage(this.imageDetails[this.curImageNumber]);
}
getNextImage(imageObj:{imageName:string,cityImageId:number,imgNumber:number}):void{
this.imgNumber= imageObj.imgNumber;this.imagePath=`assets/images/${imageObj.imageName}.png`;this.cityImageId=imageObj.cityImageId;
}
generatecityDetailArray():void{
if(this.pincode=='' || this.pincode.toString().length>6){alert('Enter Valid PinCode');return;};
this.cityDetailArray.push(
{pincode:this.pincode, cityImageId:this.cityImageId, imgNumber:this.imgNumber}
);
this.pincode='';
this.curImageNumber++;
if(this.curImageNumber==this.imageDetails.length){this.submitForm();return;}
this.getNextImage(this.imageDetails[this.curImageNumber]);
}
submitForm(){
//TODO here....
this.cityService.getAPi(this.cityDetailArray);
}
}
Model class
export class CityClassification{
pinCode : string;
cityImageId : number;
imgNumber:number;
constructor(pinCode : string, cityImageId : number,imgNumber:number){
this.pinCode = pinCode;
this.cityImageId = cityImageId;
this.imgNumber = imgNumber;
}
}
Service class
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class CityClassificationService {
imageDetails:{imageName:string,cityImageId:number,imgNumber:number}[]=[
{imageName:'Ghazipur1',cityImageId:101,imgNumber:1},
{imageName:'Nashik2',cityImageId:102,imgNumber:2},
{imageName:'Noida3',cityImageId:103,imgNumber:3}
]
constructor() { }
getAPi(formBody:any){
//API TO SUBMIT FORM.....
console.log('INSIDE SERvice.......',formBody);
}
getImageObject():any{
//API HERE TO GET IMAGE
return this.imageDetails;
}
}
here is a simple code snippet for you,
Lets say you have component name as AppComponent,
import { Component } from '#angular/core';
import {
FormBuilder,
FormGroup,
FormControl,
Validators
} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'stackoverflow-examples';
declare MultipleSelect: any;
textInputForm: FormGroup;
get textInputControl() {
return this.textInputForm.get('textInputControl') as FormControl;
}
constructor(
private fb: FormBuilder
) {
this.textInputForm = new FormGroup(
{
textInputControl: new FormControl('', [Validators.maxLength(6)])
}
);
}
ngOnInit() {
}
onClick(): void{
// Just to show you that form can read the values,
console.log(this.textInputForm.getRawValue());
}
}
Your Html can look like this below,
<form>
<label>
Input Name:
<input type="text" class="col2" [formControl]="textInputControl" maxLength="6"/>
</label>
</form>
<button (click)="onClick()">Click</button>

angular custom css class is not appening in view

I am working on angular formio, in that I am using a custom css class, name CustomCSS I have added the same in css file as follows
Here is stackblitz
app.component.scss
.CustomCSS {
margin: auto;
width: 50%;
border: 3px solid rgb(1, 248, 1);
padding: 10px;
background-color: coral;
}
app.component.ts
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
ngOnInit() {
debugger;
this.triggerRefresh = new EventEmitter();
this.http.get('http://....')
.subscribe(
response => {
this.form = response.json();// this is my html script from DB
},
err => {console.error(err)}
);
}
}
app.component.html
<formio [refresh]="triggerRefresh" [form]="form" [submission]="submission" (submit)="onSubmit($event)"></formio>
My Html this.form script as follows
{
"components":[
{
"label":"City",
"widget":"choicesjs",
"customClass":"CustomCSS",
"tableView":true,
"data":{
"values":[
{
"label":"abc",
"value":"abc"
]
},
"selectThreshold":0.3,
"calculateServer":false,
"validate":{
"required":true
},
"key":"city",
"type":"select",
"indexeddb":{
"filter":{
}
},
"input":true
},
{
"type":"button",
"label":"Submit",
"key":"submit",
"disableOnInvalid":true,
"input":true,
"tableView":false
}
],
"id":4
}
In my script also the css class name available but it is not appending in the view.
One possible way to make it work from your component is to modify the style encapsulation for that component.
import { Component, OnInit, ViewEncapsulation } from '#angular/core'; // <-- add ViewEncapsulation
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
encapsulation: ViewEncapsulation.None // <-- add this line
})
More information on encapsulation.
That being said.
I still recommend to use global styles and implement css selectors to target formio generated html elements like in your example:
#app formio .control-label {
font-weight: bold;
}

Why CSS doesn't match with Angular 6 selector component?

app.html
<app-chat></app-chat>
chat.html
<h1>Hello</h1>
chat.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
chat.css
h1 {
background-color: #000;
}
I need to know why the chat.css doesn't work in my browser. When I used CSS directly without chat component it works (like below).
app.html
<h1>Hello</h1>
app.css
h1 {
background-color: #000;
}
So what is the solution?
Try this!
::ng-deep h1{
background-color: #000;
}
Try !important in your chat.css file
h1{
background-color: #000 !important;
}
or
Use the powerful weapon of CSS style.css. But, before using it you have to set the class name for h1 tag.
chat.html
<h1 class="exampleClassName">Helo<h1>
Next, in your style.css file
.exampleClassName{
background-color: #000;
}
I did an example and it works: https://stackblitz.com/edit/angular-u99pry

move html code to a seperate html document in Angular CLI

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',
})