Encountering issues with receiving an undefined value while utilizing ngModel and ngValue in Angular 4 alongside JHipster

Objective of the Application:

I am currently developing a Web-Application using JHipster and Angular 4.

My goal is to create a select option where users can choose from displayed options using ngModel and ngValue.

Once a value is chosen, it should be shown in another HTML file. The displayed values are fetched from another entity.

recommended-section-name-dialog.component.html

<select class="form-control" id="field_locale"  name="locale" [(ngModel)]="recommendedSectionName.locale" required>
                <option [ngValue]="null"></option>
                <option
                    [ngValue]="localeOption.id === recommendedSectionName.locale?.id ? recommendedSectionName.locale : localeOption"
                    *ngFor="let localeOption of locales; trackBy: trackLocaleById">
                    {{localeOption.getName()}}
                </option>
            </select>

recommended-section-name-dialog.component.ts

import { Locale, LocaleService } from '../locale';

@Component({
    selector: 'jhi-recommended-section-name-dialog',
    templateUrl: './recommended-section-name-dialog.component.html'
})
export class RecommendedSectionNameDialogComponent implements OnInit {


    locales: Locale[];


    _recommendedSectionName: RecommendedSectionName;

    constructor(

        private recommendedSectionNameService: RecommendedSectionNameService,
   
    ) {
    }

    get recommendedSectionName(): RecommendedSectionName {
        return this._recommendedSectionName;
    }

    set recommendedSectionName(value: RecommendedSectionName) {
        this._recommendedSectionName = value;
    }

    ngOnInit() {

        if (!this.recommendedSectionName) {
            this.recommendedSectionName = new RecommendedSectionName();
        }

        this.localeService.query()
            .subscribe((res: ResponseWrapper) => { this.locales = res.json; }, (res: ResponseWrapper) => this.onError(res.json));

    }

    trackLocaleById(index: number, item: Locale) {
        return item.id;
    }
}

recommended-section-name-table.component.html

<tr *ngFor="let recommendedSectionName of rsdata ;trackBy: trackId">
            <td>{{recommendedSectionName.name}}</td>
            <td>{{recommendedSectionName.locale?.name}}</td>
</tr>

recommended-section-name-table.component.ts

@Component({
    selector: 'jhi-recommended-section-name-table',
    templateUrl: './recommended-section-name-table.component.html'
})
export class RecommendedSectionNameTableComponent {

    @Input() rsdata: RecommendedSectionName[];


    trackId(index: number, item: RecommendedSectionName) {
        if (item) {
            return item.id;
        } else {
            return null;
        }
    }

}

recommended-section-name.model.ts

import { BaseEntity } from './../../shared';
import {Locale} from "../locale";


export class RecommendedSectionName implements BaseEntity {
    constructor(
        public id?: number,
        public name?: string,
        public locale?: BaseEntity,
    ) {


    }
}

locale.model.ts

import {BaseEntity} from './../../shared';
import {Country} from '../country';
import {Language} from '../language';

export class Locale implements BaseEntity {

    public country?: Country;
    public language?: Language;
    public deleted?: boolean;

    constructor(public id?: number,
                country?: Country,
                language?: Language,
                public sponsoredProducts?: BaseEntity[]) {
        this.language = language;
        this.country = country;
        this.deleted = false;
    }

    public getName() {
        if (this.country && this.language) {
            return `${this.language.code}-${this.country.code}`;
        } else {
            return '';
        }
    }

}

Challenge Faced

When attempting to display

<td>{{recommendedSectionName.locale?.name}}</td>
in recommended-section-name-table.component.html, I do not receive any output in the browser. During debugging, I noticed that it is being set to undefined. However,
<td>{{recommendedSectionName.name}}</td>
does show an output.

Any suggestions on how to resolve this issue?

Answer №1

The problem has been resolved: The issue was not with the code that was written...

By modifying the relationship between the Recommended Section Name and Locale entities from ManyToMany to ManyToOne, the problem was successfully solved.

relationship ManyToOne {
    RecommendedSectionName {locale(name)} connected to Locale
}

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

Creating a HTTP Post request in Angular with DocRaptor to receive the download URL in the response

Struggling to integrate Angular5 with DocRaptor has led me to hit a roadblock. Surprisingly, the DocRaptor website lacks any documentation on how to combine it with Angular, only offering a beginner's guide for 'other'. I've scoured thr ...

Angular OAuth2 OIDC password reset process

Currently, I am integrating B2C into my Angular (8) application using angular-oauth2-oidc. I have successfully implemented sign-in and sign-out policies, as well as configuring the angular-oauth2-oidc service. However, when utilizing the standard Microsoft ...

Passing data to an Angular 8 router can be done easily with this simple guide

In a situation where I have a list of products on a page and wish to transmit a product ID to a /product/:id router without resorting to parsing it from the URL directly, what alternatives exist? Is there a way to implement functionality akin to an Input ...

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

What is the technique for obtaining a complete AST representation of a union type in TypeScript?

Although I am familiar with ts-ast-viewer, I am unsure of how they extract a list of elements from the union. I have experimented with different existing solutions, such as this one, but it appears that most of them are outdated. Some ts.[methods] have be ...

When working with formControlName in Angular Material 2, the placeholder may overlap the entered value

After updating my application with angular-cli to angular/material (2.0.0-beta.11) and angular (4.4.4), I noticed that every placeholder in the material input fields overlaps the value when provided with formControlName in reactive forms. However, when usi ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

Exploring Angular's HTTPClient with Test API

Recently, I developed a simple method to fetch the JSON response object from a URL API endpoint. My goal is to extract this output and place it into an element within an HTML template... Below is the function that I created for the API endpoint which ret ...

The counterpart of the RxJS setTimeout operator

Looking for a RxJS operator alternative to set/clearTimeout in these circumstances: this.mouseEnterSubscription = this.mouseEnterStream .subscribe(() => { this.timeout = setTimeout(() => { void this.playVideo(); }, 500) }); this.mo ...

Issue with Angular 5: Bootstrap Tooltip not functioning as expected

Where am I going wrong? I've been attempting to implement a Bootstrap Tooltip in Angular 5, but I'm facing some challenges. We have already set up the Javascript library through the footer of our index.html page as per the recommendations. The B ...

Looking for a specific string within all attributes of an object using Angular 2

How can I search for a specific string in all properties of an object using Angular 2 with TypeScript? I have a table displaying an array of customers and I want to implement a search feature where the user can input a value and find a customer that match ...

Choosing specific values from a dropdown menu in Angular to pass as parameters for an API call

I need to call an API with a parameter selected by the user from dropdown options. The issue I'm facing is that the API only returns results when all dropdowns are selected, not just one. I want to return results based on the single selection made by ...

Navigating through elements in Angular

I am working with multiple Angular components housed within a display:flex div container. I am fetching datatable from an API, and it contains the same number of rows as there are components. Each row in the datatable corresponds to data for each compone ...

Routing a second-level child in Angular2 directly to the root instead of the first child

I'm working on setting up a multi-level routing hierarchy for my app. It's structured like this: app |---core |---items Here is the router configuration and HTML code for my app: import { NgModule } from '@angular/core'; im ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Creating a drop-down menu in Angular 2

I'm working on my webApp and I have a menu that I want to enhance by adding a submenu. How can I achieve this? Do I need to attach a click event to the a tag with the has-sub class for each individual menu item, or is there a better solution? What sh ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

What causes the error message "Why does Angular 10 display the error 'Cannot set properties of undefined...'" to pop up?

I'm currently developing an application that allows users to sign up by providing information such as their name, nickname, password, and type of identification. Here is the user model: export class User{ id: string; name: string; nicknam ...

Modify the arrow design for the expansion panel's default arrow style

Looking to customize the design of an angular expansion panel? Check out the images below for inspiration: Before Customization: https://i.sstatic.net/4u6NS.png After Customization (Not expanded): https://i.sstatic.net/8N6Br.png After Customization (E ...

Having difficulty in utilizing localStorage to update the state

I've attempted to log back in using the stored credentials, however it's not working despite trying everything. The dispatch function is functioning properly with the form, but not when accessing localStorage. App.tsx : useEffect(() => { ...