如何在HTML标签中显示动态值?

15
假设我有一个 Angular 4 组件,代码如下:
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  printThisValue = 'customAttr';
  constructor(){}
}

如何像下面代码所示一样打印HTML标签内的值:

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

上面的HTML代码似乎无法正常工作。我知道您可以像这样打印值:

<div class="myStyle">{{ printThisValue }}</div>
// or like this
<div class="myStyle {{ printThisValue }}"></div>

但是我该怎么做呢?


5
假设您想将一个属性绑定到一个变量上,如果您知道该属性的名称,可以这样做:<div class="myStyle" [attr.customAttr]="printThisValue"></div> - dotconnor
谢谢 @dotoconnor,这是可行的,但对于像"[handle]"这样具有特殊字符的值怎么办?因为我想在标签内添加的值具有特殊字符,我相信使用[attr.[handle]]或[attr."[handle]"]不起作用。 :( - dalemncy
请查看此链接,希望您能找到所需内容:https://www.concretepage.com/angular-2/angular-2-custom-attribute-directive-example - Akhil Aravind
2个回答

12

可能有更好/更容易的方法来做这件事,但您可以创建一个指令,接受属性名称并将其设置在元素上。

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

然后你可以这样使用它:<div class="myStyle" [customAttr]="printThisValue"> , 它将被发射出去,带有<div class="myStyle" customAttr>


谢谢你的回答,伙计。 - dalemncy

1

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

情况1: 条件 属性

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



案例2:自定义(动态)属性名称

HTML(模板)

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

一个示例组件的TypeScript代码。
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,"");
    }

}

输出将会是:
<div custom_attr> Hi </div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接