如何在HTML标记上打印/显示动态值?

Dal*_*ale 15 html javascript angular

假设我有一个像这样的Angular 4组件:

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

如何在HTML标记内打印值,就像下面的代码一样:

<div class="myStyle" {{ printThisValue }} ></div>
Run Code Online (Sandbox Code Playgroud)

上面的HTML代码似乎不起作用.我知道你可以打印这样的值:

<div class="myStyle">{{ printThisValue }}</div>
// or like this
<div class="myStyle {{ printThisValue }}"></div>
Run Code Online (Sandbox Code Playgroud)

但是我该怎么做呢?

Exp*_*lls 11

可能有更好/更简单的方法来执行此操作,但您可以创建一个带有属性名称的指令,然后在元素上设置它.

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);
    }       
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像它一样使用它<div class="myStyle" [customAttr]="printThisValue">,它将被发射出来<div class="myStyle" customAttr>.