Tips for setting values to the child component property in Angular 4

When I was using ngif, I encountered an issue with getting the element reference of the child component. After extensive searching, I discovered that in order to access the element, I needed to use view children instead of view child. While I am able to get the reference to the child component, I am unable to assign values to the child properties.

In this scenario, `CorrespondenceAddressComponent` is my child component. I am trying to assign values to one of the objects (`AddressComponentMetadataDto`) within the correspondence address component from the `ManagePersonComponent` in the `SetControlsReadModeInPerson` method. However, I keep getting `undefined` when trying to assign values or call methods on the child component.

https://i.stack.imgur.com/fn3wx.png

Code snippet from ManagePersonComponent:

    
export class ManagePersonComponent extends ManagePartyComponent implements AfterViewInit  {

    ngAfterViewInit(): void {
        this.CurrentPartyType = CurrentPartyTypeEnum.Person;
        this.GetInitialDataFromService();
        this.SetControlsReadModeInPerson(this.IsReadonly);
    }

    SetControlsReadModeInPerson(isReadOnly: boolean): void {
        this.CorrespondenceAddressComponent.AddressComponentMetadataDto.IsPostalCodeDisabled = isReadOnly;
    }

Base component - ManagePartyComponent:

 
export class ManagePartyComponent extends ProjectPageComponentBase {
    @ViewChildren(CorrespondenceAddressComponent) CorrespondenceAddressComponent: CorrespondenceAddressComponent;
}

HTML:

 
<form #form="ngForm" [ngClass]="{'form-submitted' : form.submitted }" (ngSubmit)="SaveAndNavigate()">
    <toolbar [ShowSaveButton]="!IsReadonly"></toolbar>
    <p-tabView [(activeIndex)]="SelectedTabIndex">
        <p-tabPanel [header]="'Caption.CRM.CorrespondenceAddress' | translate">
            <correspondence-address [ParentForm]="form"></correspondence-address>
        </p-tabPanel>
    </p-tabView>
</form>

CorrespondenceAddressComponent:


export class CorrespondenceAddressComponent extends ProjectPageComponentBase {
    AddressComponentMetadataDto= new AddressComponentMetadataDto();

    ngOnInit():void {
    }
}

Answer №1

When using ViewChildren, you will receive a QueryList, whereas ViewChild will return a single match.

If you opt for ViewChildren, be sure to declare it accurately:

export class ManagePartyComponent extends ProjectPageComponentBase {
    @ViewChildren(CorrespondenceAddressComponent) 
    CorrespondenceAddressComponents: QueryList<CorrespondenceAddressComponent>;
}

Treat it as an enumerable like so:

SetControlsReadModeInPerson(isReadOnly: boolean): void {
   const correspondenceAddressComponent = this.CorrespondenceAddressComponents.first;
   correspondenceAddressComponent.AddressComponentMetadataDto.IsPostalCodeDisabled = isReadOnly;
}

Alternatively, use ViewChild instead:

export class ManagePartyComponent extends ProjectPageComponentBase {
    @ViewChild(CorrespondenceAddressComponent) 
    CorrespondenceAddressComponents: CorrespondenceAddressComponent;
}

This way, you do not need to work with enumerable objects. Attempting to reference AddressComponentMetadataDto on a QueryList will result in undefined, leading to errors when referencing IsPostalCodeDisabled on undefined.

It's likely that this could be the issue you are facing.

For a more detailed example similar to your scenario, check out this StackBlitz: https://stackblitz.com/edit/angular-jnqwma?file=src%2Fapp%2Fcomponents%2Fparent-component.ts

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

An error has occurred in the tipo-struttura component file in an Angular application connected with a Spring backend and SQL database. The error message indicates that there is a TypeError where the

Working on my project that combines Spring, Angular, and MYSQL, I encountered a challenge of managing three interconnected lists. The third list depends on the second one, which in turn relies on user choices made from the first list. While attempting to l ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

Modifying SASS variable within an Angular 2 TypeScript project

How can I update the Sass color variable based on user input in Angular 2? I came across a helpful resource, but it doesn't include any examples specifically for Angular 2. Any assistance would be greatly appreciated. Thank you! ...

Acquiring information from the service in Ionic 2

THE ISSUE: Apologies if this is a basic question. Within my Ionic 2 application, I have implemented a POST request for the login functionality and it is functioning correctly. The process involves a form with email and password fields, sending this data ...

Testing the Binding of Models in Angular 5 Using Jasmine Framework

I'm currently working on writing a unit test to verify that the JSON data returned from the components method call successfully links to a TypeScript model. Here's what my model looks like: export interface IPlayerAccount { playerId: number; ...

Access the properties of the encapsulated component in Vue 3, allowing for IDE autocomplete support

I have a vue3 component named MyButton which acts as a wrapper for the vuetify v-btn component. I am trying to figure out a way to make MyButton props inherit all of the props that v-btn has and also enable autocomplete feature in IntelliJ or VSCode. Is it ...

Serious issue: a dependency request is an expression (Warning from Angular CLI)

I am currently exploring the dynamic loading of lazy child routes within a lazy routing module. For example: const serverResponse = [ { path: "transaction", children: [ { path: "finance", modulePath: &qu ...

Is it possible for moduleNameMapper to exclude imports made by a module located within node_modules directory?

I am trying to figure out how to make my moduleNameMapper ignore imports from the node_modules directory. The issue is that one of the dependencies, @sendgrid/mail, uses imports starting with ./src/ which causes problems when importing into Jest. My curre ...

Ensuring the proper export of global.d.ts in an npm package

I'm looking to release a typescript npm package with embedded types, and my file structure is set up like so dist/ [...see below] src/ global.d.ts index.ts otherfile.ts test/ examples/ To illustrate, the global.d.ts file contains typings ...

Issue with file uploading in Angular 9 as the uploaded file is not being added to the

I've set up a form group in the HTML of my Angular 9 app that includes an upload feature for files. The file upload works fine when calling the handleFileInput function, as I can confirm from the console log output. However, even though the file gets ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...

Exploring the functionality of the Angular 7 date pipe in a more dynamic approach by incorporating it within a template literal using backticks, specifically

I have a value called changes.lastUpdatedTime.currentValue which is set to 1540460704884. I am looking to format this value using a pipe for date formatting. For example, I want to achieve something like this: {{lastUpdatedTime | date:'short'}} ...

Searching for a particular Prettier setting

Seeking a Nicer alternative. I am exploring if there is a way to format code like this without moving the first attribute to a new line: <div class="test-class" [test-binding]="true" (test-binging)="test()" ...

Sending an image in the body of an HTTP request using Angular 7

I'm currently in the process of developing an Angular application that captures an image from a webcam every second and sends it to a REST API endpoint for analysis. To achieve this, I have implemented an interval observable that captures video from t ...

Setting up the Font Awesome Pro version in Angular using the Font-Awesome package

The process of installing the pro version of Angular Font-awesome began with setting up my registry using these commands: npm config set "@fortawesome:registry" https://npm.fontawesome.com/ && \ npm config set "//npm.fontawesome.com/:_authTo ...

What is the proper way to incorporate types in a universal function?

Encountering an issue with TypeScript while using a universal function export const createNewArray = <T>( arr: T[], keyId: keyof T, keyTitle: keyof T, ) : [] | TValue[] => { const arrayAfterMap = arr.map((item) => ({name: item[ ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

Struggling to grasp the syntax of RxJS filter

Trying to wrap my head around a filter expression in an Ionic/Angular project. Here's the code snippet: private userId$ = this.authService.currentUserAuth$.pipe( filter(user => !!user), map((user) => user.uid) ); The authservice is of ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

I encountered an eslint error when I was trying to configure Vue 3 + Quasar with a Firebase config.ts file. The error stated that there was an unsafe assignment of an `

Recently, I set up a new Vue 3 project with Quasar using the Quasar CLI. In order to store my firebase configuration, I created a new file called src/firebase/config.ts, which looks like this: // Import necessary functions from SDKs import { initializeApp ...