Issue
I am new to Angular. Tried to make a button/badge component. But when I am trying to use it more than one time, the css are getting overlapped and misbehaving. I think that when new instance of the badge component got created the second time, it overwrote on the first one, not sure.
app.html
<div class="container">
<app-badge [title]="'First'" [bgColor]="'Green'"></app-badge>
<app-badge [title]="'Second'" [bgColor]="'Blue'"></app-badge>
</div>
badge.html
<div class="container">
{{title}}
</div>
badge.ts
import { Component, ElementRef, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-badge',
templateUrl: './badge.component.html',
styleUrls: ['./badge.component.css']
})
export class BadgeComponent implements OnInit {
@Input()
title : String="Badge";
@Input()
bgColor : String="";
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit(){
const ele = (document.getElementsByClassName('container')[0]);
ele.setAttribute("style", `background-color:${this.bgColor};`);
}
}
Solution
Yes that's exactly what is happening like you explained, when second app-badge
is rendered it will also overwrite the first one's background to blue.
First app-badge
is rendered as Green
.
Then second app-badge
is rendered as Blue
.
When second blue app-badge
is rendered you are effectively saying this: Take the first [0]
element from container
and set this background to this.bgColor
which is Blue. So now the first app-badge
which is green turns to blue and now their both blue.
const ele = (document.getElementsByClassName('container')[0]);
ele.setAttribute("style", `background-color:${this.bgColor};`);
I suggest you to remove document manipulation altogether:
ngAfterViewInit(){
const ele = (document.getElementsByClassName('container')[0]);
ele.setAttribute("style", `background-color:${this.bgColor};`);
}
And change the color in badge.component.html
using NgStyle
(I don't know what you have in there, but it would go something like this):
<div [style.background-color]="bgColor">
https://angular.io/api/common/NgStyle
Answered By - Joosep Parts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.