Angular2: Component View encountered an unexpected directive value of 'undefined'

My Angular2 Application requires me to showcase a list of questions that editors can generate. Each question can have 0 to n answers (options - such as 'yes', 'no', '5', etc.). To achieve this, I need to load the AnswerComponent from my QuestionComponent.

Furthermore, each answer may lead to 0-1 follow-up questions. This implies that I also have to load the QuestionComponent from the AnswerComponent.

For reference, here is a plunker: http://plnkr.co/edit/1itBVtDu8TD8Etxo4JZh

The simplified QuestionComponent:

@Component({
    selector: 'copyright-question',
    template: `
                <div class="col-md-8">
                    <strong>{{ question?.content }}</strong>
                    <div class="row-actions">
                        <span *ngIf="!question?.isAnswer" class="addAnswer"><button (click)="onAddAnswer()">Add Answer</button></span>
                    </div>
                </div>,

                <li *ngFor="let answer of question.answers">
                    <copyright-answer [answer]="answer"></copyright-answer> 
                </li> 
    `,
    directives: [AnswerComponent]
})

The simplified AnswerComponent:

@Component({
    selector: 'copyright-answer',
    template: `
            <ul class="col-md-12">
                <li><strong>{{ answer.answerTxt }}</strong></li>
                <li>
                    <div class="row-actions">
                        <span>
                            <span><button (click)="onQuestionSave()">Add follow-up question</button></span>
                        </span>
                    </div>
                </li>

                <!-- Follow Up Question -->
                <li>
                  <copyright-question [question]="copyrightQuestion"></copyright-question>
                </li>
            </ul>
    `,
    directives: [QuestionComponent]
})

After extensive research for over 3 days, it's clear that there is a circular dependency issue. Unfortunately, I am unsure how to resolve this. The requirement is to offer an arbitrary sequence length of questions and answers. I attempted forward referencing but encountered the following error message:

EXCEPTION: Unexpected directive value 'undefined' on the View of component 'AnswerComponent'

For your information, the application serves as a backend for an ionic app. Users are required to respond to questions, which may lead to follow-up questions or a final result (also considered a question technically).

If this question appears duplicated, kindly guide me to an existing solution. However, I couldn't find one that caters to components nested in this manner.

Thank you very much!!!

Answer №1

/**
 * Revised by Brudus on 11/06/16.
 */
import {Component, OnInit, Input, forwardRef} from "@angular/core";
import {Question} from "./question";
import {Answer} from "./answer";
import {QuestionComponent} from "./question.component";

@Component({
    selector: 'copyright-answer',
    template: `
            <ul *ngIf="answer" class="col-md-12">
                <li><strong>{{ answer.answerTxt }}</strong></li>
                <li>
                    <div class="row-actions">
                        <span>
                            <span><button (click)="onQuestionSave()">Add follow-up question</button></span>
                        </span>
                    </div>
                </li>

                <!-- Follow Up Question -->
                <li *ngIf="copyrightQuestion">
                  <copyright-question [question]="copyrightQuestion"></copyright-question>
                </li>
            </ul>
    `,
    directives: [forwardRef(() => QuestionComponent)]
})

export class AnswerComponent implements OnInit {
    @Input() answer: Answer;

    copyrightQuestion: Question = null;

    constructor() {}

    ngOnInit() {

    }

    onQuestionSave() {
      //content: string, isAnswer: boolean, answers?: Answer[], 
        //        isRoot?: boolean, parentQuestion?: string

        const question: Question = new Question('Follow-up question', false, null,
        false, null);
        this.copyrightQuestion = question;
    }
}

Answer №2

Experiment with the Elvis operator ?. within string interpolation.

{{ response?.responseText }}

If response is falsy (undefined, null, etc.), it will not retrieve the responseText attribute.

response will remain as null until a reply is received.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for mocking a method from a class that is instantiated within another class using ts mockito in typescript?

I have a specific Class that I want to test using the mocha-chai testing framework in TypeScript. My approach involves incorporating ts-mockito for mocking purposes. export class MainClass implements IMainClass { private mainResource: IMainResource; ...

A guide on implementing localStorageService in the configuration of $translateProvider module

When working with MEANjs, I incorporated angular-translate and angular-local-storage into my module dependencies. In the app config.js file: var service = { applicationEnvironment: window.env, applicationModuleName: applicationModuleName, a ...

Concealing Enclosures in Jade - AngularJS Syntax

Struggling with writing this in Jade, specifically the .get() function is giving me trouble. <li ng-repeat="breadcrumb in breadcrumbs.get() track by breadcrumb.path" ng-class="{ active: $last }"></li> Seen from: https://github.com/ianwalter/n ...

What is the recommended approach for returning two different types in a TypeScript function?

My API function currently performs a post request and returns an Observable of ModelAResponse, which is an interface I have defined. I now want to modify this function so that it can return an Observable of either ModelAResponse or ModelBResponse based on ...

What are the steps for personalizing themes in the Monaco editor?

I'm currently working on a code editor with Monaco. The syntax highlighting in Monaco for Javascript and Typescript only highlights keywords as dark blue, strings as brown, and numbers as light greenish-yellow. My goal is to customize the vs-dark the ...

Encountering an issue with core.js:15723 showing ERROR TypeError: Unable to access property 'toLowerCase' of an undefined value while using Angular 7

Below, I have provided my code which utilizes the lazyLoading Module. Please review my code and identify any errors. Currently facing TypeError: Cannot read property 'toLowerCase' of undefined in Angular 7. Model Class: export class C_data { ...

What is the collection of types that accept a parameterized argument?

I am working with an item interface that looks like this: interface Item<Href extends string> { href: Route<Href> } My goal is to create a component that accepts a list of these Item objects as a single property: interface Props { items: I ...

Custom headers in AngularJS $resource

After encountering a few challenges with understanding, I have come across some difficult issues. I am struggling to make my custom headers work on the $request from AngularJS. The code snippet in question is as follows: $scope.re = $resource('/&apos ...

Tips for keeping the information current from one generation to the next

Is there a way to pass data from a parent component to a child component using template binding (on ngInit), and then have the same updated data shared between them without involving a service or other methods? I experimented with the following template: ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...

What is the best way to choose multiple elements within an Angular application?

<div class="modalmenu" > <div class="modal_itm" (mouseenter)="sepin(sepinout)" (mouseleave)="sepout(sepinout)"><a href="#in">HOME</a></div> <div class="sep" # ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Progress bar for file download is not visible on the browser

I have developed an Angular application that utilizes an ASP.NET Web API. My goal is to enable users to download files stored on my server. The current code I am using for this functionality is as follows: [HttpGet] [Route("downloadFile")] [JwtAuthentica ...

Angular Error cli command Error: In order to proceed, please provide a command. To see a list of available commands, use '--help'

When I run any command with Angular CLI, I encounter an error. To resolve this issue, I attempted to uninstall and reinstall it by running the following commands: npm uninstall -g @angular/cli npm install -g @angular/cli However, the problem persists an ...

What could be the reason behind the failure of $cookieStore.get() in retrieving the value?

I am currently testing the cookie functionality in AngularJS. I'm encountering an issue where the console is returning 'undefined' when trying to retrieve a saved value from the cookie using $cookieStore.put(). It seems to work fine when set ...

Is there a way to identify legitimate contacts and phone numbers within an Android application using Javascript or Typescript?

I am developing an Android app where I need to show a list of contacts and specify if they are part of the app's network. However, my goal is to only display valid contacts while excluding unwanted ones such as toll-free numbers or data balance check ...

Make a reference to a specific element within an Angular component and access

There are two images to choose from, and based on your selection using ng-click, the class changes. When moving on to the next step, a new object is created to store references to the selected image: $scope.cabinetDetails.cabinetType = { name: $scope. ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

React-Bootstrap columns are not displaying in a side by side manner and are instead appearing on separate lines

I am currently integrating Bootstrap into my React project alongside Material UI components. Below is a sample of one of my components: import { styled } from "@mui/material/styles"; import Paper from "@mui/material/Paper"; import Cont ...