Utilizing Angular and Typescript for Enhanced Modal Functionality: Implementing Bootstrap Modals in Various Components

When working in Angular, I have a component called Modal. I need to open the same Modal Component from two different places. The catch is, I want the button text in the Banner image to say "Get Started Now". Check out the Image linked below for reference.

https://i.stack.imgur.com/4LPp3.png

Below is the code snippet from modal.component.html with the button included.

<div class="modal-here">    
    <ng-template #content let-modal>
      <div class="modal-header">
        <h4 class="modal-title">Modal 1</h4>
        <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal 1 body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button>
      </div>
    </ng-template>
    <button class="btn post-task" (click)="openVerticallyCentered(content)">Post a task</button>
</div>

Here is the TypeScript code from modal.component.ts

import { Component, OnInit } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'app-modal',
    templateUrl: './modal.component.html',
    styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

    closeResult: string;

    constructor(private modalService: NgbModal) {}

    ngOnInit(): void {
    }

    openVerticallyCentered(content) {
        this.modalService.open(content, { centered: true, windowClass: 'setClass' });
    }

}

In the header.component.html TypeScript code, I aim to use the same modal with the same button text as previously placed

<header>
    <nav class="container navbar navbar-expand-md fixed-top nav-setting">
        <!-- Main logo links here -->
        <ul class="navbar-nav mr-auto left-menu">
            <app-modal></app-modal>
            <!-- Other left menu items go here -->
        </ul>
        <div class="admin-side">
            <ul class="navbar-nav ml-auto right-menu">
                <!-- Right menu items -->
            </ul>
        </div>
    </nav>
</header>

Let's provide the app.component.html banner TypeScript code which requires the same modal but with the button text changed to "Get Started Now"

<app-header></app-header>
<div class="content" role="main">
    <div class="container-fluid banner position-relative">
        <div class="row bg-image">
          <div class="col-sm-12"></div>
        </div>  
        <div class="row align-items-center banner-content position-absolute m-0 w-100">
            <div class="col-sm-12">
                <div class="custome-container">
                    <h1 class="title banner-title">
                      Connect with experts to get the job done on Airtasker
                    </h1>
                    <p class="description banner-text">
                        It’s amazing what you can’t do yourself
                    </p>
                    <div class="banner-button">
                        <app-modal></app-modal>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<app-footer></app-footer>
<router-outlet></router-outlet>

CSS styling for all the provided code snippets can be found down below.

@font-face {
  font-family: Museo Sans Regular;
  src: url(assets/Fonts/MuseoSans-300.otf);
}
/* Rest of the CSS styles */

The desired output image is presented below for illustration purposes.

https://i.stack.imgur.com/hBt4k.png

Answer №1

To implement a variable in the modal component, start by adding a new variable in the modal.component.ts file and then reference its value in the modal.component.html file.

_btnLabel: string = '';

Next, utilize @Input to access input values:

@Input()
set btnLabel(value) {
    this._btnLabel = value;
}

You can now display this value in the modal.component.html file:

<button>{{_btnLabel}}</button>

In the component where you require this value, define a variable. For example, in header.component.ts, set a variable with the desired value:


_header: string = "Post a task";

Access this defined value in the corresponding HTML file, such as header.component.html:


<app-modal [btnLabel] = "_header"></app-modal>

Answer №2

textToDisplay: string;

@Input() buttonText: string;

}

By incorporating the component in your HTML, you can define the text for the button on the modal window by using <app-modal [buttonText]="Click Here to Begin"> or <app-modal [buttonText]="Submit a Request">

<button class="btn request-submit" (click)="showModal(content)">{{buttonText}}</button>

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

Postpone the NgModule declaration by importing the module asynchronously

I am facing a challenge in dynamically importing a third-party module and then checking if it exists. The decision to declare it in the NgModule depends on its existence (true/false). Below is an example of my code. However, the issue arises because the ...

Switch between active tabs (Typescript)

I am working with an array of tabs and here is the code snippet: const navTabs: ITab[] = [ { Name: allTab, Icon: 'gs-all', Selected: true }, { Name: sources.corporateResources, Icon: 'gs-resources', Selected: false }, { Name ...

Instead of displaying the name, HTML reveals the ID

I have defined a status enum with different values such as Draft, Publish, OnHold, and Completed. export enum status { Draft = 1, Publish = 2, OnHold = 3, Completed = 4 } In my TypeScript file, I set the courseStatus variable to have a de ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

Utilizing TypeScript typing with the Express Request object

Encountering an issue with Typescript typings involving the Express Request object. The project is comprised of 2 sub-projects, the user-service and a common project containing reusable Errors and Middlewares. The common folder is added as a dependency in ...

What is the best way to replicate certain key-value pairs in an array of objects?

I am working with an array of objects. resources=[{name:'x', title:'xx',..},{name:'y',title:'yy',..}..] To populate my HTML tooltip, I am pushing all the titles from the resources array to a new array. dialogOkCli ...

A function that takes in a type identifier and a portion of a type, and then outputs the full type

I'm currently facing a challenge with TypeScript generics. I have several types (referred to as Animals) that each have a unique attribute, "type." Additionally, I have a function called createAnimal which takes the type of animal and a partial object ...

What are the steps to generate a customizable datatable with various columns and information?

My application allows users to select options from a dropdown menu, which triggers a request and displays the output - typically a table - on the website. The data is always in JSON format, like the examples shown below: '{"columns":["C1","C2"], "dat ...

What is the process for converting an image into base 64 using Angular 5?

Is there a way to convert an image into base 64 using angular5 when the image is sourced from Facebook or Google authentication API? I seem to be encountering an issue, what could I be doing wrong? getBase64Image(img) { var canvas = document.createEleme ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

What is the importance of adding the ".js" extension when importing a custom module in Typescript?

This is a basic test involving async/await, where I have created a module with a simple class to handle delays mymodule.ts: export class foo { public async delay(t: number) { console.log("returning promise"); ...

Angular 6 secure access control

To prevent unauthorized access, if a user is not logged in and attempts to access a secure URL, they should be redirected to the login page. Even if the URL is directly entered in the browser's address bar. I came across a solution on this website th ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Tips on toggling the visibility of an element in Angular 4

This is my unique html element: <ng-container> <span *ngIf="row.messageText && row.messageText.length >= 30 && expanded">{{row.messageText.substr(0, 25)}} <span>more</span> </span> ...

Leverage environment variables within your index.html file

Currently, I am using Angular and I am encountering an issue while attempting to utilize an environment variable in my index.html for Google Analytics. I have attempted the following approach: <script> import {environment} from "./environments/e ...

Unexpected issue with Ionic 4 subarray returning as undefined even though the index is accurate

When attempting to use console.log to view the value, I noticed that the value of noticeSet2[index] is undefined. However, when I print noticeSet, all the data in the array is displayed. Additionally, after printing the index using console.log, it correctl ...

The module has defined the component locally, however, it has not been made available for

I have developed a collaborative module where I declared and exported the necessary component for use in other modules. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DateslideCompone ...

I am having trouble with the TypeScript compiler options not being detected in Visual Studio 2015

After creating an ASP.NET 5 Empty Website project in Visual Studio 2015, I set up a tsconfig.json file with the following settings: { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...