如何在HTML标记上打印/显示动态值?
16lz
2021-01-22
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>
.
然后你可以使用它:
它将与 一起发出。更多相关文章
- 解决FCKEditor编辑器在浏览器返回时显示html源代码的问题
- 高分求:如何解析IdHTTP获得的http代码?用mshttp的IHTMLDocument2可
- 韩顺平_轻松搞定网页设计(html+css+javascript)_第19讲_js运行原
- HTML显示日期时间代码 - [js 特效代码]
- 解决html代码中插入的图片在浏览器中不显示的办法
- HTML代码格式化工具
- j2ee的web项目,有最终的html代码(即f12看到的最终给用户浏览器展示
- 如果字符串包含html代码,如何用python检测?
- 【竞价网站绝技】根据访客ip,页面显示访客所属城市的html代码(借用