0

Object is possibly 'undefined'. I'm getting an error, my codes are as seen below, what do you think is the problem?

enter image description here

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  serverElements = [{type: 'server', name:'TestS',content:'Just'}];

}

app.component.html

<div class="container">
  <app-cockpit></app-cockpit>
  <hr>
  <div class="row">
    <div class="col-xs-12">
      <app-server-element
      *ngFor="let serverElement of serverElements"
      [element]="serverElement">  </app-server-element>
    </div>
  </div>
</div>

app.server-element-component.html

<div
class="panel panel-default">
<div class="panel-heading">{{ element.name }}</div>
<div class="panel-body">
  <p>
    <strong *ngIf="element.type === 'server'" style="color: red">{{ element.content }}</strong>
    <em *ngIf="element.type === 'blueprint'">{{ element.content }}</em>
  </p>
</div>
</div>

and server-element-component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-server-element',
  templateUrl: './server-element.component.html',
  styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit {

  @Input() public element:  { type: string; name: string; content: string; } | undefined;

  constructor() {
  }

  ngOnInit(): void {    
  }

}
VolkanUstekidag
  • 345
  • 2
  • 8
  • The error message is straightforward - what about it are you having trouble understanding? Remember that your `ServerElementComponent` component can exist without its `element` property being set, so the `{{ element.content }}` expression will fail at runtime. – Dai Oct 30 '21 at 11:18
  • It's been a while since I've done any Angular, but I think you can remove the type `undefined` from the line `@Input() public element...` and set a default value for the `element` object in the constructor to avoid this issue. – Timo Oct 30 '21 at 11:27

0 Answers0