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. Then you can use it like: <div class="myStyle" [customAttr]="printThisValue"> and it will be emitted with <div class="myStyle" customAttr> .
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With