【发布时间】:2021-02-13 12:18:12
【问题描述】:
如果打印了案例 3 和“Accepted your offer”,我正在尝试将文本的背景设为绿色。我想使用 elementRef 访问 DOM 和 javascript 以使用 if 语句添加背景颜色。我在我的 component.ts 文件后面添加了 if 语句,但是它破坏了程序,在此之前它工作正常并且打印正确。控制台上不显示任何错误消息。如何使用此方法实现更改背景颜色所需的行为?提前致谢。这是我的 .component.ts 和 .html 文件:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@ViewChild('latestSystemMessage', { static: true })
latestSystemMessage: ElementRef;
export class MessagesComponent implements OnInit {
getLatestSystemMessage(thread: Thread): string {
const message = thread.messages.slice().reverse().find(m => m.type !== 0);
const isUserOwner = thread.project.user.id === this.user.id;
let content = '';
if (message) {
switch (message.type) {
case 1:
if (<any>message.content > 0) {
content = isUserOwner ?
`Offered you $${message.content}` :
`You offered $${message.content}`;
} else {
content = isUserOwner ?
`Offered to translate for free` :
`You offered to translate for free`;
}
break;
case 2:
content = isUserOwner ?
'Cancelled offer' :
'You cancelled your offer';
break;
case 3:
content = isUserOwner ?
'You accepted the offer' :
'Accepted your offer';
break;
case 4:
content = isUserOwner ?
"You accepted another translator's offer" :
"Accepted another translator's offer";
break;
}
}
if(this.latestSystemMessage.nativeElement === "Accepted your offer" ){
this.latestSystemMessage.nativeElement.style.backgroundColor="green";
}else{};
return content;
}
这是我的 .html 文件
<p class="mb-0" #latestSystemMessage><strong>{{getLatestSystemMessage(thread)}}</strong></p>
【问题讨论】:
-
你可以借助 html 文件中的绑定来实现。不使用这种方法有什么具体原因吗?
-
@SudiptoMukherjee 是的,这行得通……我只是想知道为什么这种方法不起作用,所以我可以从我在这里做错的事情中吸取教训
标签: angular elementref