Encountering difficulty in retrieving value through the get method, resorting to interpolation. The value from the getTitle() method for 'this._title' is not being displayed

import { Component } from '@angular/core';

@Component({
    selector: 'courses',
    template: '<h1>{{ getTitle() }}</h1>'  ////issue with not displaying 'this._title' value???
})

export class CoursesComponent{
    private _title: string;

    set Title(x: string){
        this._title = x;
    }

    getTitle(): string{                //function to retrieve title 
        return this._title;        
    }
}

let courseObj = new CoursesComponent;
courseObj.Title = 'List of Courses';

Answer №1

Things don't always work as expected. Try using ngInit to set up your component and values.

https://angular.io/api/core/OnInit


import { Component } from '@angular/core';

@Component({
    selector: 'courses',
    template: '<h1>{{ getTitle() }}</h1>'  ////why isn't 'this._title' being displayed???
})

export class CoursesComponent implements OnInit {
    private _title: string;

    set Title(x: string){
        this._title = x;
    }

    getTitle(): string{                //method 
        return this._title;        
    }
    ngOnInit() { this.Title = 'List of Courses'; }
}

Angular handles the creation of components in its engine. Essentially, when you include a component in an HTML file, Angular identifies which class to use, runs the constructor, and if it includes on init, it will run that method.

In your code, you defined a component but never utilized it within Angular. Although you set the title, the component was not added to any view.

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

Transform a list of time slots into a time interval using Angular (2/4/5/6)

Hello everyone! Just wanted to share my updated solution after considering your feedback. Thank you! getTime(apptTime) { const fields = apptTime.split("-"); const startingTime = this.formatTime(+fields[0]); const endingTime = this.formatTime(+fie ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Setting up pagination in Angular Material can sometimes present challenges

After implementing pagination and following the guidelines provided here. This is my code from the app.component.ts file - import { Component, OnInit, ViewChild } from '@angular/core'; import {MatPaginator} from '@angular/material/paginat ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

The signal property 'ɵunwrapWritableSignal' is not found on the specified type 'typeof import/node_modules/@angular/core/index")'

Despite attempting the solutions provided in previous threads, none of them have been successful for me. Can someone please lend a hand with this issue? https://i.stack.imgur.com/sGRsn.png ...

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

The Angular2 Ng Date Time picker appears oversized upon opening

Utilizing the Ng Date Time picker in conjunction with Angular2 frontend, which can be found at: I attempted to replicate the examples from this source: https://stackblitz.com/github/DanielYKPan/owl-examples/tree/date-time-picker?file=src%2Fmain.ts I ins ...

The issue encountered is: "Unable to assign property 'id' to a numeric value of '1' in Angular."

In my Angular 7 project, I am trying to establish a client-side request to the server-side. Below is the structure of the request that needs to be sent. { "title" : "Test Title", "user": { "id" : 7 ...

Error with the ng-select component in an Angular 8 project - Issue at Runtime involving the NgSelectComponent

I'm encountering issues with implementing ng-select in my Angular 8 application. The error I'm facing at runtime is: core.js:6249 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[NgSelectComponent -> NgSele ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

Refreshing Angular 2 + Firebase app causes user to be logged out

Just diving into Angular2, Firebase, and SPAs for the first time. I've been tasked with enhancing a Angular2 (with Firebase email&pw auth) application by adding some new features. The app primarily consists of a blog (main page), a shop (/shop), a ...

Adjustable image within a div based on the length of the title when viewed in Edge browser

I am facing an issue with a div element. Here is the code snippet: <div fxLayout="column" fxLayoutGap="20px"> <h1 class="mat-display-1">Welcome to $TITLE$</h1> <img *ngIf="logoData" [src]="logoData" class="logo" alt="logo"/> &l ...

Angular's change detection is currently inactive

I need to toggle the visibility of a button based on the value of a boolean variable using the Output property. However, I am facing an issue where the button remains hidden even after the variable is updated with a true value. Parent Component.ts showE ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Ionic 4's http.get.subscribe method fails to retain the retrieved value

I'm aware this might be a repeated question, but I haven't come across a straightforward answer yet, so here it goes. Below is the code snippet in question: fetchData() { let dataArray: Array<any> = [, , ,]; this.prepareDataReque ...

The Angular2 application encountered a 404 file not found error while trying to read a Const from a ts

Recently I started working with angular2 and encountered a problem when trying to access constant values from an external .ts file using the following code: import {apis} from '../constants/apis'; The content of the constants/apis.ts file is as ...

Angular function implementing a promise with a return statement and using the then method

I have a function in which I need to return an empty string twice (see return ''. When I use catch error, it is functioning properly. However, I am struggling to modify the function so that the catch error is no longer needed. This is my current ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...

What is the best way to send an action based on the HTTP method being used?

I've been utilizing NGXS for handling state in my angular project. What would be considered a best practice? Should I make the HTTP call first and then dispatch an action within its subscription? Or should I dispatch the action first and then make t ...