Angular / Typescript – Use a base class for common functions

We are in the process of re-writing our components to be stand-alone and re-useable. Please note we are using Angular 16, and can not upgrade to a newer version yet.

I’m trying to create a base class to handle error messages, loading, and other common functionality. In this base class, I have a behavior subject that is not being updated, other than in the ngOnInit. What I’m trying to do is to pass a boolean to show that the service call was successful, and show a false in the base.component.html:6

I’ve tried various things, with no success. Maybe I’m missing something obvious with how base classes work in typescript versus what I’m used to in C#.

Thanks in advance, here’s the stackblitz: https://stackblitz.com/edit/stackblitz-starters-r6ncxp?file=README.md

app.component.html

<div class="content" role="main">
  This is from the app.component.html
  <app-home></app-home>
</div>

base.component.ts

import { CommonModule } from "@angular/common";
import { Component, Input, OnInit, TemplateRef } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Component({
  selector: 'app-base',
  templateUrl: './base.component.html',
  styleUrls: ['./base.component.scss'],
  standalone: true,
  imports: [CommonModule],
})
export class BaseComponent implements OnInit {
    @Input() templateRef: TemplateRef<any> | null = null;     // reference to the child template to be projected
    isLoading$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);

    constructor() { }

    ngOnInit() {
      // if I call this from the home component, then isLoading$ updates
    }

    handleEvent(foo: any) {
      console.log(`from handleTestLoadingEvent: ${foo}.`);
      this.isLoading$.next(foo);

    }

    inheritEvent(foo: boolean) {
      console.log(`base component inheritEvent value: ${foo}`);
      this.isLoading$.next(foo);
    }
}

base.component.html

<div>
  <p>
    This is the base.component.html
  </p>
  <p>
    isLoading$: {{ isLoading$ | async }}
  </p>
  <ng-container *ngTemplateOutlet='templateRef' (isLoading)="handleEvent($event)"></ng-container>
</div>

home.component.ts

import { Component, EventEmitter, OnInit, Output, TemplateRef } from '@angular/core';
import { BaseComponent } from '../base.component';
import { FooService } from '../service/foo.service';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  standalone: true,
  imports: [BaseComponent, CommonModule],
  providers: [FooService]
})
export class HomeComponent extends BaseComponent implements OnInit {
  @Output() isLoading: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(private fooService: FooService) {
    super();
   }

  override ngOnInit(): void {
    // Emit this to the base component
    this.fooService.getFoo(1234).subscribe(f => {
      console.log(`foo Service has been called successfully: ${f}`);
      this.isLoading.emit(f);
      this.inheritEvent(f);
    });
  }
}

home.component.ts

<app-base [templateRef]='homeTemplate'>
  <ng-template #homeTemplate>
    This is from home.component.html
  </ng-template>
</app-base>

5

i Would recommend you to change your design, but in the meanwhile lets work with this.

There are some changes you need to make to fix this:

1.- The ng-container does not support Output so the BaseComponent nevers get called with the (isLoading).

2.- The BaseComponent is created twice, one from the extends from HomeComponent an another from the declaration tag so you are dealing with two instances.

3.- There is a cyclic dependency between HomeComponent and BaseComponent.

Now lets fix those issued to make it work.

In the HomeComponent use the @ViewChild to access the instance of the base-component, and delete the extends, then replace the access to BaseComponent with the instance.

  @ViewChild(BaseComponent, { read: BaseComponent, static: true })
  base!: BaseComponent;

Create a new class (An standalone directive) i called CommonComponent (rename it to whatever you want) and make HomeComponent to extends it, with this will be able to inject any component in the BaseComponent.

@Directive({ standalone: true })
export class CommonComponent {
  @Output() isLoading: EventEmitter<boolean> = new EventEmitter<boolean>();
}

In the HomeComponent providers, provide the new class with the existing HomeComponent.

  providers: [
    FooService,
    { provide: CommonComponent, useExisting: HomeComponent },
  ],

And last, inject into the BaseComponent the CommonComponent (remember this can be any component that was provided) and subscribe to the events of it.

  constructor(private component: CommonComponent) {
    console.log('BaseComponent!');
  }

  ngOnInit() {
    this.component.isLoading.asObservable().subscribe((e) => {
      this.handleEvent(e);
    });
  }

Now you are able to communicate between the decoupled components.

This is the example of your project https://stackblitz.com/edit/stackblitz-starters-hxyvl4 in case i missed something.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật