0

Using a store, I subscribed to all the changes for a particular item. I want to output these changes (terminal message) in an angular component (ng-terminal). The code completion suggests me the method write. This also works outside of ngOnInit(). The output via the Console works. The control is also present (this.terminal != null).

H

import {AfterViewInit, Component, Input, OnInit, ViewChild,} from '@angular/core';
import { select, Store } from '@ngrx/store';
**import { NgTerminal } from 'ng-terminal';**
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { terminalSelector } from 'src/app/stores/terminal/terminal.selectors';

@Component({
    selector: 'simu-terminal',
    templateUrl: './terminal.component.html',
    styleUrls: ['./terminal.component.scss'],
})
export class TerminalComponent implements OnInit, AfterViewInit {
    @Input() content: TerminalComponent;
    @ViewChild('term', { static: true }) terminal: NgTerminal;

    private readonly unsubscribe$ = new Subject<void>();

    constructor(private readonly store: Store) {}

    ngOnInit(): void {
        this.store
            .pipe(select(terminalSelector), takeUntil(this.unsubscribe$))
            .subscribe((msg) => {
                console.log(msg.message);
                if (this.terminal != null) {
                    this.terminal.write(msg.message);
                }
            });
    }

   ngAfterViewInit() {
        this.terminal.keyEventInput.subscribe((e) => {
            console.log('keyboard event:' + e.domEvent.keyCode + ', ' + e.key);
            const ev = e.domEvent;
            const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey;
            if (ev.keyCode === 13) {
                this.terminal.write('\r\n$ ');
            } else if (ev.keyCode === 8) {
                if (this.terminal.underlying.buffer.active.cursorX > 2) {
                    this.terminal.write('\b \b');
                }
            } else if (printable) {
                this.terminal.write(e.key);
            }
        });
    }
}

But inside ngOnInit I get the following message:

core.js:6498 ERROR TypeError: Cannot read properties of undefined (reading 'write')
    at NgTerminalComponent.write (ng-terminal.js:241)
    at SafeSubscriber._next (terminal.component.ts:33)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at TakeUntilSubscriber._next (Subscriber.js:72)
    at TakeUntilSubscriber.next (Subscriber.js:49)
    at DistinctUntilChangedSubscriber._next (distinctUntilChanged.js:50)
    at DistinctUntilChangedSubscriber.next (Subscriber.js:49)

What am I doing wrong?

Holgis
  • 43
  • 1
  • 5

1 Answers1

0

You can just insert a ? between the property name and the period between the next property:

this.terminal?.write('\b \b');
pzaenger
  • 11,381
  • 3
  • 45
  • 46