How to print/show a dynamic value on an HTML tag?

  • A+
Category:Languages

So assuming that I have an Angular 4 component like this:

@Component({   selector: 'app-home',   templateUrl: './home.component.html',   styleUrls: ['./home.component.css'], }) export class HomeComponent implements OnInit {   printThisValue = 'customAttr';   constructor(){} } 

How to I print the value inside an HTML tag just like this code seen below:

<div class="myStyle" {{ printThisValue }} ></div> 

The HTML code above seems to not work. I'm aware that you are able to print the value like this:

<div class="myStyle">{{ printThisValue }}</div> // or like this <div class="myStyle {{ printThisValue }}"></div> 

But how do I go about this?

 


There may be a better / easier way to do this, but you can create a directive that takes the name of the attribute and then sets it on the element.

import { Directive, Input, ElementRef, AfterViewInit } from '@angular/core';  @Directive({    selector: '[customAttr]'  }) export class CustomDirective implements AfterViewInit {     @Input() customAttr;     constructor(private elRef: ElementRef) {}      ngAfterViewInit() {        this.elRef.nativeElement.setAttribute(this.custom, true);     }        } 

Then you can use it like: <div class="myStyle" [customAttr]="printThisValue"> and it will be emitted with <div class="myStyle" customAttr>.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: