Dale
Dale

Reputation: 619

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?

Upvotes: 15

Views: 9340

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191749

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>.

Upvotes: 12

Debojyoti
Debojyoti

Reputation: 4841

Check which one can be your solution

Case 1 : Conditional attribute

<div class="myStyle" [attr.attr_name]="condition"></div>



Case 2 : Customized (dynamic) attribute name

HTML (Template)

<div #elem1>
  {{ attachAttr }} Hi
</div>

TypeScript of a Sample Component

import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  myAttr = "custom_attr"; // Customize attribute name

  attachAttr: any;

  @ViewChildren('elem1') elem;

  ngAfterViewInit() {
    this.elem['first'].nativeElement.setAttribute(this.myAttr,"");
    }

}

Output will be

<div custom_attr> Hi </div>

Upvotes: 1

Related Questions