【问题标题】:How to print/show a dynamic value on an HTML tag?如何在 HTML 标签上打印/显示动态值?
【发布时间】:2018-12-16 17:02:03
【问题描述】:

所以假设我有一个像这样的 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>

但是我该怎么做呢?

【问题讨论】:

  • 假设你想绑定一个属性到一个变量;如果你知道你可以做的属性名称:&lt;div class="myStyle" [attr.customAttr]="printThisValue"&gt;&lt;/div&gt;
  • 谢谢@dotoconnor,这可以工作,但是具有特殊字符(如“[handle]”)的值呢,因为我想在标签中添加的值有一个特殊字符,我相信做 [attr.[handle]] 或 [attr."[handle]"] 不起作用。 :(
  • concretepage.com/angular-2/…查看这个链接,希望你能得到你需要的东西

标签: javascript html angular


【解决方案1】:

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

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

然后您可以像这样使用它:&lt;div class="myStyle" [customAttr]="printThisValue"&gt;,它将与 &lt;div class="myStyle" customAttr&gt; 一起发出。

【讨论】:

  • 感谢朋友的回答。
【解决方案2】:

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

案例1:条件属性

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



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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2014-07-18
    • 2016-05-21
    • 2021-08-23
    相关资源
    最近更新 更多