如果打印案例 3 和“接受您的报价”,我正在尝试使文本的背景变为绿色。我想使用 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>