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

Can a string be used to retrieve a templateRef?

Can a TemplateRef be acquired by passing a string? I am intrigued by this possibility. I'm not looking to obtain it through a component's HTML; rather, I want to store it in a configuration file that can be used across all components. Specifical ...

Creating custom components in AngularJS 2 allows you to define methods unique to each component. Want to learn

I created my component (A) by combining multiple html elements, but I have two questions. How do I define methods (such as get, etc.) on my component? I have tried @Output, @ViewChild, etc. but they are not working. I am looking for an alternative way ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

Can ng-content be utilized within the app-root component?

I have successfully developed an Angular application, and now I am looking to integrate it with a content management system that generates static pages. In order to achieve this, I need to utilize content projection from the main index.html file. The desi ...

Unexpected behavior observed with field alignment

I've been attempting to align the field in an Angular HTML page, but it's not working out as I expected. Here's how the HTML file looks: <div id="report-prj-search"> <div class="dx-fieldset flex-column"> <div class="fle ...

The element 'p-checkbox' is unrecognized in primeng version 4

Currently utilizing primeng version 4. I have included a p-checkbox in my template and imported it to the respective TypeScript file. However, upon loading the page in the browser, an error stating "'p-checkbox' is not a known element" keeps appe ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Why should TypeScript interfaces be utilized in Angular services for defining type information?

What are the benefits of creating an interface for an Angular service as opposed to simply exporting the service class and using that for type information? For example: class Dashboard { constructor(ui: IUiService){} } vs class Dashboard { cons ...

Generating a type definition from a JavaScript file

Looking to convert a .js file to a d.ts file, I've noticed that most resources on this topic are from 2 years ago How do you produce a .d.ts "typings" definition file from an existing JavaScript library? My question is, after 2 years, is there a simp ...

Binding user input to a preset value in Angular with data binding

My goal is to have a predefined input form with the email provider value preset. However, when I try to submit the form without modifying it, it does not upload anything to Firebase unless I manually delete the value and re-enter it. <input class="butt ...

Hiding columns in TanStack Ver 8: A step-by-step guide

Can someone assist me with dynamically hiding specific columns in Tanstack table ver 8? I have a column defined as follows: { header: "Case Number", accessorKey: "caseNumber", visible: false, // using this value ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Passing data from the main component to a component with a different route is a common practice in

In my main component home.component.ts, I have the following code: ngOnInit() { this.metaService.getMetaCompany() .subscribe((response: Json) => { let metaCompany = <MetaCompany>response.data; this.interactionService.setGlobalMet ...

Retrieve the current step index in Angular Material Design Stepper

In my endeavors to retrieve the selected step within a component utilizing Angular Material Design stepper, I am encountering some issues. My current approach involves using the selectedIndex property, but it consistently returns "1" instead of the desire ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Dealing with null exceptions in Angular 4: Best practices

Hi there, I am encountering an issue with binding my model data to HTML fields where when I try to edit the data it returns an error saying "cannot read value of null". How can I resolve this? Here is the HTML code snippet: <div class="form-group"> ...

What is the process for transmitting an array of objects from Angular to a Web API Core using HttpGet?

In my TypeScript file, I have an array of objects called PropertiesParams: const PropertiesParams = [{ Name: 'FirstName', Filter: 'Like1' }, { Name: 'LastName', Filter: 'Like2' }, { Name: ...

What is the proper way to select an item by clicking and then navigate to the corresponding component in a p-dropdown menu?

To view the options available in the p-dropdown, I made changes to the class City. Now, this class has an additional property called url, which specifies the path of a component. I have designed the dropdown as follows: interface City { name: string; ...

Issue with Angular ngFor binding. What could be causing this error to occur?

I have a main component called DOCUMENT. This document receives a URL segment and retrieves an array of associated objects from my database. Then, using @Output() documents = new EventEmitter() and an @Input() in a DOCUMENT VIEW component, I loop through t ...