Ways to activate an Angular controller function when the internal status is altered?

What is the optimal approach for ensuring that my Angular component triggers the bound method (referred to as isItemExpended in this scenario) whenever changes occur in the internal data model?

TypeScript

@Component({
  ...
})
export class ItemsComponent implements OnInit {
  ...

  private expandedItems: Item[] = [];

  public isItemExpanded(item: Item): boolean {
    return this.expandedItems.indexOf(item) > -1;
  }
 
  ...
}

HTML

<ng-container *ngFor="let item of items">
  <div *ngIf="isItemExpanded(item)">
    ...
  </div>
</ng-container>

Note: My solution involves a slightly more intricate implementation of the isItemExpaned method, hence why I've avoided placing the condition directly in the HTML.

Answer №1

@Component({
  ...
})
export class ItemsComponent implements OnInit {
  ...
  constructor(private changeDetector: ChangeDetectorRef){}

  private expandedItemsList: Item[] = [];

  public checkIfItemIsExpanded(item: Item): boolean {
    return this.expandedItemsList.indexOf(item) > -1;
  }

  private subscribeToModelChanges() {
     model.changed$.subscribe() {this.changeDetector.markForCheck()}
  }
  ...
}

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

When a user clicks on empty space in Angular 2, the page will automatically redirect

When I receive a response from the server, I want to redirect to another page. However, this process takes around 60 seconds, so in the meantime, I want to display a spinner. Once the response is received, I should be redirected to the new page. Sounds sim ...

Activate the child for an update

Welcome! I am a newcomer to Angular and would greatly appreciate any assistance. The parent component of my picker has the ability to create various rules for each option. However, these rules are dynamic and can change frequently. I need to ensure that ...

Unable to load dynamic JSON data in ag-grid for Angular 2

ngOnInit(){ this.gridOptions = {}; this.gridOptions.rowData = []; this.gridOptions.rowData = [ {configName: 1, configName1: "Jarryd", configName2: "Hayne", configName3: "tttttt", configName4: "rrrtttt", configName5:"drrrrrr"}]; } ...

Duplicated RxJs in Angular 5 with Webpack 4 and Rxjs 5 DllPlugin - a common issue plaguing

My current configuration includes: "webpack": "4.12.0", "rxjs": "5.5.9", "@angular" : "5.2.11" and I am bundling libraries with the DDL Plugin. { entry: {"rxjs_5_5_9": [ "rxjs ], "angular_5_2_11": [ "@angular/common", ...

Problem with subscribing to observable

As part of a service, I have the following code: return this.httpClient.get<Country[]>('http://localhost:8080/countries'); While it passes unit tests with mocked values, it fails to assign relevant values to a variable when used in the ng ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

`Unable to upload spreadsheet file in xlsx format`

I'm currently working on implementing a feature to export data as xlsx files. I have been successful in exporting CSV and PDF formats, but encountered issues with the xlsx format due to dynamic imports. export const exportToXlsx = async ( gridElemen ...

Enhancing MUI themes by incorporating module augmentation for multiple typings

I am looking to create a repository with two directories, each using MUI and TypeScript. Both directories will have their own theme defined in one ThemeProvider per root. In the main index.tsx file in the root directory, I want to specify which component t ...

The color rendering of objects in the b3dm file is not displayed correctly by three.js

Currently, I am working on converting a file with a .b3dm extension to a .glft and then displaying it by loading it in three.js. For guidance, I am referring mainly to an interesting article. However, I seem to be facing an issue where the object is only ...

I am having trouble retrieving the group attribute from the FormBuilder within my reactive form in React

Issue with 'group' property in 'FormBuilder' type See below for the code snippet import { FormBuilder, FormGroup, Validators } from '@angular/forms'; export class LoginPageForm{ constructor(private formBuilder = FormBuild ...

Is there a way for me to pass the templateUrl data from the parent component to another component

Currently, I am in the process of learning Angular2 and facing a situation where I have a dropdown that appears on multiple pages. Each time it is called, the contents of the dropdown change, but the structure remains the same. This is why I have set it up ...

What happens in Angular when there is an implicit change handler for ngModel without specifying ngModelChange?

My expertise lies in utilizing [(ngModel)] for achieving two-way value binding between a component field and a form control in the component's template. I am also well-versed in using (ngModelChange) to execute additional tasks when the value changes. ...

Utilizing Angular to upload videos

I'm having an issue while attempting to upload a video using Angular and send it to a PHP backend server. Currently, I am working with Angular 6 and have utilized ng2-file-upload. While this method works well for images, when I attempt to send a vide ...

Webpack and React.js: Additional loaders might be required to manage the output generated by these loaders

An error occurred while parsing the module in ./productFlow/index.tsx at line 3, column 12. The file was processed with the following loaders: * ./node_modules/awesome-typescript-loader/dist/entry.js. It seems like an additional loader may be needed to h ...

React-Redux button unit test in Vitest encounters failure

I'm struggling with passing a button click test in my app component using Vitest, react-testing-library, and jest dom. As a newcomer to unit testing, I'm having difficulty figuring out how to make my test for the submit button in my form function ...

Utilizing the array.map method to access the key of an object within an array of arrays in TypeScript

Can I utilize array.map in TypeScript to apply a function with the parameter being the key of an object within an array? I have an array containing objects which have keys 'min' and 'max'. I am looking to use something like someArrayFun ...

What is the best way to incorporate node_module during the iOS build process in Ionic 2?

Looking to implement an autosize module for automatic resizing of an ion-textarea. Module: Following the installation instructions, I tested it in the browser (ionic serve) and on my iPhone (ionic build ios => run with xcode). Browser: The module wor ...

Troubleshooting problem with fetching data from Angular API

Looking to use Angular to extract a specific value from the following API: Current code snippet being utilized: app.controller("api", function($scope, $http) { $scope.home = "This is the homepage"; $scope.getRequest = function() { console. ...

What causes type checks to be skipped when spreads are used on type-guarded types?

Query: Why doesn't a compile-time error occur when I overlook adding nested fields to an object of type T, while constructing the object using object spread? Illustration: interface User { userId: number; profile: { username: string } } f ...

What is the best way to programmatically click on an element within the body of a webpage from an Angular component?

I am running a crisp chat service on my website and I am attempting to interact with the chat box from one of my component's typescript files. The chat box is represented as a div element with the id crisp-client inside the body tag. Can someone plea ...