Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 226
Dale Moncayo Avatar asked Jul 09 '18 04:07

Dale Moncayo


People also ask

How do I print dynamic value in HTML?

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

What is dynamic content in HTML?

Dynamic content in the context of HTML and websites refers to website content that constantly or regularly changes based on user interactions, timing and other parameters that determine what content is delivered to the user.


1 Answers

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.customAttr, true);
    }       
}

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

like image 92
Explosion Pills Avatar answered Oct 11 '22 02:10

Explosion Pills