So assuming that I have an Angular 4 component like this:

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

@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:

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

<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:

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

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

But how do I go about this?

但是我该怎么做呢?

2 个解决方案

#1


11

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>.

然后你可以使用它:

它将与 一起发出。

更多相关文章

  1. 解决FCKEditor编辑器在浏览器返回时显示html源代码的问题
  2. 高分求:如何解析IdHTTP获得的http代码?用mshttp的IHTMLDocument2可
  3. 韩顺平_轻松搞定网页设计(html+css+javascript)_第19讲_js运行原
  4. HTML显示日期时间代码 - [js 特效代码]
  5. 解决html代码中插入的图片在浏览器中不显示的办法
  6. HTML代码格式化工具
  7. j2ee的web项目,有最终的html代码(即f12看到的最终给用户浏览器展示
  8. 如果字符串包含html代码,如何用python检测?
  9. 【竞价网站绝技】根据访客ip,页面显示访客所属城市的html代码(借用

随机推荐

  1. Android多线程(三)HandlerThread源码原理解
  2. 一个查看xhprof数据文件的docker镜像
  3. 教你用php读写csv格式的文件
  4. 详解PHP位运算符
  5. 初学php,你遇到过这个低级问题吗?
  6. 一个php框架的简单实现,仅实现简单路由层
  7. 关于PHP打印格式化显示利器
  8. PHP常见数组排序方法小汇总
  9. php实现断点续传大文件
  10. 数组转json后的结果是数组还是对象? (踩坑