Angular 4 applies same directive to all divs within iteration -
i faced strange behaviour in angular. want render div , style according information comes database.
template
<div *ngfor="let app of apps" > <div appapplicationcolor [name]="app.name.az"> <a href="{{app.url}}?token={{token}}" target="_blank"> <p>{{app.name.az}} </p> </a> </div> </div> app.name.az ="Əlavə", 'lms' , 'mhs' , appapplicationcolor directive
component
@directive({ selector: '[appapplicationcolor]' }) export class applicationcolordirective implements oninit, ondestroy { @input() name: string; constructor(private elementref: elementref , private renderer: renderer2) { } ngoninit() { if (this.name = 'Əlavə') { this.renderer.setstyle(this.elementref.nativeelement, 'background-color', 'yellow'); } else if (this.name = 'lms') { this.renderer.setstyle(this.elementref.nativeelement, 'background-color', 'red'); } else if (this.name = 'mhs') { this.renderer.setstyle(this.elementref.nativeelement, 'background-color' , 'green'); } else { this.renderer.setstyle(this.elementref.nativeelement, 'background-color', 'blue'); } console.log(this.name) } } the problem divs become yellow instead of according app.name.az. strange when inspect divs [name] , app.url different in each. console outputs 'Əlavə' 3 times means angular directive not change [name] property dynamically.
this because in check using
if (this.name = 'Əlavə') { this set name 'Əlavə' - should instead use === (see: difference between == , ===)
if (this.name === 'Əlavə') { but in case better using switch statement this
switch (this.name) { case 'Əlavə': this.renderer.setstyle(this.elementref.nativeelement, 'background-color', 'yellow'); break; case 'lms': this.renderer.setstyle(this.elementref.nativeelement, 'background-color', 'red'); break; case 'mhs': break; this.renderer.setstyle(this.elementref.nativeelement, 'background-color' , 'green'); break; default: this.renderer.setstyle(this.elementref.nativeelement, 'background-color', 'blue'); }
Comments
Post a Comment