我有这样的代码:.html:
<div *ngIf="isNotificationDisplayed" class="notification">
<h2 align="center" class="set-margin" id="notification">Node was...!</h2>
<h3 align="center">Press any key to hide it</h3>
</div>
和.ts:
import { Component, OnInit, HostListener } from '@angular/core';
@Component({
selector: 'app-notifications',
templateUrl: './notifications.component.html',
styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {
isNotificationDisplayed: boolean = false;
notification: any = document.getElementById("notification");
constructor() { }
ngOnInit(): void {
}
@HostListener('document:keydown', ['$event'])
handleKeyDownKeyboardEvent(e: KeyboardEvent) {
if (e) {
this.isNotificationDisplayed = false;
}
}
isCreated(name: string) {
this.notification.value = `Node ${name} was created!`;
this.isNotificationDisplayed = true;
}
isUpdated(name: string) {
this.notification.value = `Node ${name} was updated!`;
this.isNotificationDisplayed = true;
}
isDeleted(name: string) {
this.notification.value = `Node ${name} was deleted!`;
this.isNotificationDisplayed = true;
}
}
但每次我尝试获取h2标头时,notification=null。我不知道是否可以像输入一样改变h2值。
您必须使用innerHTML
。如MDN 所述
Element属性innerHTML获取或设置HTML或XML标记包含在元素中。
阅读更多信息并查看此处的示例。
#notification
不是表单输入。表单输入值可以通过修改value
属性来更改。但这对其他DOM元素不起作用。要实现这一点,您必须使用以下其中之一:innerHTML
、innerText
或textContent
。建议使用后两者。
isCreated(name: string) {
this.notification.textContent = `Node ${name} was created!`;
this.isNotificationDisplayed = true;
}