Tips for extending a class with a constructor parameter of type "Title" in Angular's platform-browser type parameter

I am trying to manipulate the web-page's title using the following method:

GetTitle.ts

import { Title }     from '@angular/platform-browser';
......
export class GetTitle {

    public constructor(private titleService: Title ) { }

    public setTitle( newTitle: string) {
      this.titleService.setTitle( newTitle );
    }
}  

However, I am now faced with a new challenge. I want to create a new Sub-Class that inherits from this one.
How should I define a constructor in the child TestGetTitleClass?
How can I instantiate an object of the parent GetTitle class?

TestGetTitleClass.ts

import {GetTitle} from "../path..";
let getTitleInstance : GetTitle = new GetTitle( ??? ?? );

export class TestGetTitleClass extends GetTitle{
   constructor(){
       super( ???? );
   }
}

Answer №1

If you're looking to understand how a certain code works, I can provide you with a snippet from one of my previous projects:

Explaining ComponentViewRightMode Class : This specific class is designed to determine the user's rights based on the URL using the ApplicationService and relying on the Router.

export class ComponentViewRightMode {
    private _routerReference: Router;
    private _applicationsServiceReference: ApplicationsService;
    viewRight: string;

    constructor(
        router: Router,
        applicationsService: ApplicationsService
    ) {
        this._routerReference = router;
        this._applicationsServiceReference = applicationsService;
        this.getCurrentUserViewRight();
    }

    getCurrentUserViewRight() {
        this.viewRight = this._applicationsServiceReference.currentViewReadMode(this._routerReference.url);
    }
}

Understanding StockComponent Class : Pay attention to how dependencies are injected using super().

export class StockComponent extends ComponentViewRightMode implements OnInit {

    constructor(
      private router: Router,
      private applicationsService: ApplicationsService,
      ...
    ) {
      super(router, applicationsService);
    } 
}

In essence, my goal was to share the viewRight property across multiple components by utilizing the method described above. Due to the property being set in the constructor of the parent Class, all the child components could access it asynchronously through my services.

This enables me to utilize the property in my templates effectively, as shown below:

Example of StockComponent Template :

<div class="stock-actions">
  >>>>> This is where the viewRight property comes into play <<<<<
  <button [disabled]="viewRight !== 'Write'" md-raised-button (click)="navigateTo('someURL')">
    {{'STOCK.EQUIPMENT_ADD'|translate}}
  </button>
  ...
</div>

I hope this practical demonstration assists you in gaining a better understanding.

Answer №2

If you're looking for a suggestion, I would recommend giving this approach a try:

Consider creating a Parent class (you could define it as an abstract class) like so:

export abstract class Titler {
  constructor(protected title: string) {}
}

The use of the protected keyword indicates that the method or property is only accessible internally within the class or any extending classes, not externally.

Next, design your Child class:

export class TestTitler extends Titler {
  constructor(protected title: string) {
     super(title);
  }
}

And finally, consider implementing a SuperChild class (this is just an example):

export class SuperChildTestTitler extends TestTitler {
  anyWayDoTitle(){
    return this.title;
  }
}

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

TS2349 emerges when incorporating lazy-loading in React

I've been working on refactoring a React 18 app to incorporate lazy loading, following the guidelines provided in the official documentation: One effective method to implement code-splitting in your application is through the dynamic import() syntax ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

What sets apart an inlined return type from a return type defined in a separate type definition within a function?

I'm experiencing inconsistent behavior when I specify the return type of a function inline compared to defining it in a separate type definition. For instance: interface Foo { bar: string; } type Fooer = () => Foo; const foo1: Fooer = () =& ...

Navigating in Angular2 - Altering query parameters on the same page

In my project using Angular 2, I am working on a Component with a datatable that supports paging and sorting. My goal is to update the URL Parameters every time the table page/size and sorting change. When accessing this component via the Router, I also w ...

Configuration error with MultiCapabilities

Encountering an issue while utilizing multiCapabilities with two web browsers (Firefox and Chrome). Below is a snippet from my configuration: exports.config = { allScriptsTimeout: 11000, seleniumAddress: 'http://localhost:4444/wd/hub', b ...

Having trouble applying CSS while printing using the ngx-print library in Angular 14. Can anyone help me out with this issue

The table shown in the image is experiencing issues with applying CSS properties when printing. While the background graphics feature has been enabled, the preview section still does not reflect the CSS styling. What could be causing this discrepancy? Cli ...

I'm facing an issue where I am unable to commit the Angular folder in my project using IntelliJ or SourceTree with

I am currently working on a web app project that includes a folder with a PHP API REST and another folder with Angular files. Strangely, when I try to commit my files to BitBucket, everything gets committed except the files under the Angular folder. Simil ...

Incorporating visuals into Stripe checkout sessions for various products

I am currently integrating the Stripe payment gateway into my Next.js application. I have multiple products that need to be added for checkout, but I encountered an error when trying to include images in the product_data for the line_items. It seems that ...

Issue with Angular modal not opening as expected when triggered programmatically

I am working with the ng-bootstrap modal component import { NgbModal, ModalCloseReasons } from "@ng-bootstrap/ng-bootstrap"; When I click on a button, the modal opens as expected <button class="btn labelbtn accountbtn customnavbtn" ...

Understanding the NavigationContainer reference in Typescript and react-navigation

In my current project with react-navigation, I've come across a scenario where I need to navigate from outside of a component (specifically after receiving a push notification). The challenge is that when I use the navigation.navigate method from wit ...

Angular has a way of causing confusion when it comes to differentiating between anchor scrolling and wildcard routing, denoted by

I am facing an issue in my Angular project where anchor scrolling is conflicting with wildcard routes. Here is what I have done in the project: I have enabled anchor scrolling in my app.module.ts like this: RouterModule.forRoot( [ { path: &ap ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Using TypeScript, retrieve the primary email address from a list of multiple email addresses within React Table

I need to retrieve the default email from the data obtained through an API The data is structured like this: { "id": "123", "firstName": "Man", "lastName": "Stranger", "emailAddresse ...

What are the best scenarios for creating a constructor in Angular 2 using Typescript?

Check out these sample constructors I found in the Angular 2 documentation: export class AppComponent implements OnInit { title = 'Tour of heroes'; heroes: Hero[]; selectedHero: Hero; constructor(private heroService: HeroService ...

Each property of an object has its own unique key, yet they all share the same data type

I have a single-use object with only three properties, all of which should be of the same type. The code below currently achieves this, but I'm curious if there is a more efficient way to declare the type for timingsObject: let timingsObject: ...

What could be the reason for the Angular2 Component property not appearing on my webpage?

Here is the code snippet I am working with: import {Component} from "@angular/core"; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <h2>{{secondTitle}}</h2> <main-page></ma ...

The combination of React, Typescript, and MaterialUI Paper results in a stunning design with a sleek and

Whenever I include <Paper elevation={0} /> within my react component, I encounter the following issue: Cannot read properties of undefined (reading 'background') TypeError: Cannot read properties of undefined (reading 'background&apos ...

Updating the function type definition in TypeScript after importing it into a separate file

I have created a unique hook named useDropdownSelection. It's a straightforward one. Take a look at the code below: import { useState } from 'react' export const useDropdownSelection = (initialValue: string) => { const [selectedOption, ...

Tips for implementing absolute paths and baseUrl in TypeScript compiler

When I bundle a package using tsc, I am getting incorrect output. Here is the structure of my project directory: common └── index.ts types ├── action.ts ├── index.ts └── request.ts utils ├── event.ts ├── index.ts ├─ ...

An Error occurred: Unable to resolve all parameters for 'ComponentName': ([object Object], ?)

I am encountering an error that I can't seem to figure out. compiler.js:2175 Uncaught Error: Can't resolve all parameters for ClauseListComponent: ([object Object], ?). at syntaxError (compiler.js:2175) at CompileMetadataResolver._getDependencie ...