Home > Software engineering >  How can I get h2-header and manipulate with its value?
How can I get h2-header and manipulate with its value?

Time:08-01

I have this code: .html:

<div *ngIf="isNotificationDisplayed" >
  <h2 align="center"  id="notification">Node was...!</h2>
  <h3 align="center">Press any key to hide it</h3>
</div>

and .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;
  }
}

But every time I try to get h2-header, notification = null. And I don't know if it's possible to change h2 value in the same way as it's possible with Input.

CodePudding user response:

You have to use innerHTML. As mentioned on MDN

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.

Read more and see examples here.

CodePudding user response:

#notification is not a form input. Form input values can be changed by modifying value attribute. But that doesn't work for other DOM elements. To achieve this, you have to use one of: innerHTML, innerText, or textContent. Use of the latter two is advised.

isCreated(name: string) {
    this.notification.textContent = `Node ${name} was created!`;
    this.isNotificationDisplayed = true;
  }
  • Related