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

Javascript 如何在HTML标记上打印/显示动态值?,javascript,html,angular,Javascript,Html,Angular,假设我有一个角度为4的分量,如下所示: @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) export class HomeComponent implements OnInit { printThisValue = 'customAttr'; constructor(){} } <div cl

假设我有一个角度为4的分量,如下所示:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  printThisValue = 'customAttr';
  constructor(){}
}
<div class="myStyle">{{ printThisValue }}</div>
// or like this
<div class="myStyle {{ printThisValue }}"></div>
如何打印HTML标记中的值,如下所示:

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

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  printThisValue = 'customAttr';
  constructor(){}
}
<div class="myStyle">{{ printThisValue }}</div>
// or like this
<div class="myStyle {{ printThisValue }}"></div>
{{printThisValue}
//还是像这样

但是我该怎么做呢?

检查哪一个可以成为您的解决方案

案例1:条件属性

<div class="myStyle" [attr.attr_name]="condition"></div>
输出将是

<div custom_attr> Hi </div>
Hi

可能有更好/更简单的方法来实现这一点,但您可以创建一个以属性名称命名的指令,然后在元素上设置它

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);
    }       
}

然后您可以像这样使用它:
,它将与

一起发出,假设您要将属性绑定到变量;如果您知道可以执行的属性的名称:
谢谢@dotoconnor,这可能会起作用,但是对于具有特殊字符的值,例如“[handle]”,又如何呢?因为我想在标记中添加的值有一个特殊字符,我相信执行[attr.[handle]]或[attr.[handle]]是不起作用的(查看此链接,我希望你能得到你需要的。谢谢你的回答,伙计。