Leveraging accessors in the Angular component's HTML template

I have a data model class called QuestionDataModel, like this:

class QuestionDataModel {
    body: string;
    
    constructor(bodyValue: string) {
        this.body = bodyValue;
    }  
}

In my component html template, I'm trying to display the body content of each question in a table row. Here's how I tried to do it:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <!-- other columns skipped --> 

  <ng-container matColumnDef="body">
    <th mat-header-cell *matHeaderCellDef>Question Body</th>
    <td mat-cell *matCellDef="let oneQuestion">
      {{ oneQuestion.bodyForTableRow }}
    </td>
  </ng-container>
</table>

But instead of displaying the modified body with line breaks replaced by "//" symbols, it shows empty rows.

I also tried using the original getter function oneQuestion.body, and that works correctly. So why is the modified version not working?


UPDATE

When I log the response from the REST call in the console, I can see that the dataSource array is populated with QuestionDataModel objects. But for some reason, the modified version of the body content doesn't render properly in the table rows.

Answer №1

It seems like what you're attempting should work, however there may be another issue at play such as incorrect instantiation of your class. It might be beneficial to consider restructuring your code to utilize a setter instead...

class Question {
    private _body: string;

    set body(body: string) {
      this.bodyForTableRow = body.replace("\n", " // ");
      this._body = body;
    }
    get body() {
      return this._body;
    }
    
    bodyForTableRow: string;
}

Angular's change detection system evaluates functions on every cycle, so placing the replace method in a getter means it will run on each cycle. By using this structure, you are only running and setting it when necessary.

To make use of this or any class, remember to instantiate it using the new keyword,

this.oneQuestion = new Question();
this.oneQuestion.body = 'my string with line returns \n next line';

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

Troubleshooting issue: Angular 7 navigation function not functioning within an 'if' statement

AppComponent.ts if(result['status'] === 'success'){ this.router.navigate(['/dashboard']) //return false alert("Login successful!"); } else { alert("Invalid login credentials"); } The "Login successful!" aler ...

Upgrading from Angular 5 to Angular 7: A seamless migration journey

Following my migration from Angular 5 to Angular 7, I encountered an issue with RxJs operations such as observables and @ngrx/store. Here is the error message I received: ERROR in node_modules/@ngrx/store/src/actions_subject.d.ts(2,10): error TS2305: Mo ...

Creating Dynamic Types in TypeScript Based on React State

As part of my project, I am developing a versatile useFetch hook that will be responsible for handling data fetching operations. The hook should return an object with different properties based on whether the fetch operation was successful or encountered a ...

Executing click on an HTML file element using a component in Angular 2

As a newcomer to Angular 2, I have a question: How can I trigger a click on an HTML file element from a component? rankingFilter() { this.RepsloaderShow = true; this.reps = []; var data = { from: this.fromFilter, to: this.to ...

Issue encountered during Angular Build: Unable to recognize version 64 of op_mob

Encountering an error during the Jenkins build process for my angular application. Strangely, it builds without any errors in my local development environment. ./node_modules/bootstrap/dist/css/bootstrap.min.css - Error: Module build failed (from ./node_mo ...

SonarQube detects unfamiliar language in Angular project - The second line in the report is mentioning a file with an unidentified language

I recently set up my Angular project with SonarQube, but I'm encountering an exception. ERROR: While running the SonarQube Scanner, I encountered the following issues: ERROR: There was a problem parsing the generic test execution report located at &a ...

Learning the implementation of uib-tabset in Angular 2 with ng-bootstrap

Currently, I am working on an angular2 project and I am curious to know if there is a way to utilize uib-tabset in angular2. In the past, when I was using angularjs, I could easily use ng-bootstrap. This allowed me to incorporate <uib-tabset></u ...

Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently wor ...

Obtain the last used row in column A of an Excel sheet using Javascript Excel API by mimicking the VBA function `Range("A104857

Currently in the process of converting a few VBA macros to Office Script and stumbled upon an interesting trick: lastRow_in_t = Worksheets("in_t").Range("A1048576").End(xlUp).Row How would one begin translating this line of code into Typescript/Office Scr ...

Merge two observables together to create a single observable that emits values from both sources. Only one observable will emit values

I am looking to combine two observables of type T[] obtained from httpservice. I have tried using forkJoin and zip, but they both return an Observable of type [T[], T[]]. However, I want to receive an object of type T[] as shown in the following code snip ...

webpack is having trouble locating the src file, even though it should not be searching for it in the first place

I'm currently delving into the world of using TypeScript with React and am following a helpful tutorial at: https://blog.logrocket.com/how-why-a-guide-to-using-typescript-with-react-fffb76c61614 However, when attempting to run the webpack command thr ...

Is it possible to substitute a name for an ID in a request?

Currently, I am following a tutorial on angular.io at https://angular.io/tutorial/toh-pt6#get-hero-by-id. It made me think if there is a way to use names instead of ids to send requests or is it hardcoded that only numbers can be used as ids? getHero(id ...

Tips for creating a carousel with Angular 9 to showcase numerous items

I've got this code snippet that I'm working on. I want to incorporate a Carousel feature using Angular 9 without relying on any external libraries. Currently, all the data items are appearing in a single row (they are exceeding the specified bor ...

Obtaining the accurate return type based on the generic parameter in a generic function

Is there a way to determine the correct return type of a function that depends on a generic argument? function f1<T>(o: T) { return { a: o } } // How can we set T to number through (n: number)? type T1 = typeof f1 extends (n: number) => infe ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

Why is the bearing attribute important in determining the location of an object?

I have started using this plugin to enable GPS functionality in my app. If you are interested, the link to the plugin can be found here: https://github.com/mauron85/cordova-plugin-background-geolocation My question is about the bearing property of the lo ...

Experiencing an abundance of issues with html-webpack-plugin while incorporating TypeScript

I am working on a project that involves using Webpack and TypeScript. However, when attempting to run the development server, I encountered numerous errors related to the html-webpack-plugin. This is a snippet of the output: > [email protected] dev ...

Typescript - Certain implementations may eliminate the optionality of properties

After exploring multiple versions of the Omit implementation, including the one displayed by Intellisense when hovering over Omit, I'm struggling to grasp why certain implementations are homomorphic while others are not. Through my investigation, I&a ...

Angular 5 - Error: Uncaught ReferenceError: req variable is not defined

After upgrading my Angular project from version 4.4.3 to 5, I made sure to update all angular packages to the latest Angular 5.0.0 as per the guidelines provided. Additionally, I updated the angular CLI to version 1.5.0. However, ever since this update, I ...

Angular debounce applied exclusively to user input

In my Angular2 project, I have implemented a reactive form. Within one of my components, I am subscribing to the value changes of a form control with a debounce time of 500ms using the following code: myForm.get("myField").valueChanges.debounceTime(500).s ...