Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string.

I tried following an example in the Hero Angular App, but I keep encountering issues with @Input and @Output directives.

Can someone provide a clear and concise example of how I can achieve this without any complications?

I have two components: the AppComponent and another component called InfoComponent.

In the AppComponent:

HTML


<nav class="navbar" role="navigation" aria-label="main navigation">
<button value="for_api">button</button>
</nav>
<router-outlet></router-outlet>

TS


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
apiFeed = "string_for_link"
}

Then there's the Info Component that gets rendered through the Router Outlet (disregard the RouterLink)


import { Component, EventEmitter, OnInit } from '@angular/core';
import {MatTabsModule} from '@angular/material/tabs';
import {MatListModule} from '@angular/material/list'; 
import { Observable } from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { size } from 'lodash';

@Component({
  selector: 'app-info',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.css']
})
export class InfoComponent implements OnInit {
  
  constructor(private http: HttpClient ) {

  }


  ngOnInit(){
this.http.get('redacted_for_privacy' + **api_feed**).subscribe(infos => {this.infosData = [infos as any];});
}
}

I've attempted various approaches to implementing two-way binding, but none seem to work for me. I'm relatively new to this.

My goal is for the value of the button in the AppComponent to be bound to api_feed, which would then be used in the Info Component to update the API link.

Please assist me with this issue.

There must be a straightforward solution to this problem. Please demonstrate.

Thank you

Answer №1

Here is an example:

Sub html

<button (click)="action.emit('foo')">Do Foo</button> <br>
<button (click)="action.emit('bar')">Do Bar</button>

Sub TS

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html'
})
export class DetailsComponent {
  @Output() action = new EventEmitter()
}

Main HTML

<app-details (action)="handleEvent($event)"></app-details>

Main TS

handleEvent(event: any) {
    console.log(`https://api.example.com/v1/endpoint?q=${event}`)
}

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

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

Incorporate a new method into a TypeScript class from a separate file

I'm curious about the feasibility of adding additional functions to a class prototype in Typescript. Here's my dilemma: I have a file containing a class, for example image.ts: export class Image { b64img: string; } Since this class is gene ...

Enhancing a Given Interface with TypeScript Generics

I am looking to implement generics in an Angular service so that users can input an array of any interface/class/type they desire, with the stipulation that the type must extend an interface provided by the service. It may sound complex, but here's a ...

RxJS mergeMap waits for the completion of inner Observables before moving on to

I encountered an issue with my solution that initially appeared to be working, but when tested on a slow network: public getKeyFigureValuesForAllClients(keyFigurename: string) { const keyFigureDefintion$ = this.keyFigureDefintions$.pipe( flatMap ...

Unraveling the Intricacies of Manipulating Values through mockStore.overrideSelector

There is a certain selector that I'm working with, and it returns either true or false. To ensure accurate testing in my unit test, I need to cover scenarios where this value is both true and false. To set up for the test, I have initially configured ...

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

Incorporate additional fields into the info.plist file for a Cordova iOS application

I am in the process of developing a custom plugin that will automatically add entries to the info.plist file for an iOS application built with Cordova and Angular 4. One specific entry I need to include triggers the application to exit when the home button ...

Tips for utilizing PNG images in Next.js beyond the conventional PUBLIC folder

I have been trying to use images from a directory other than the Public folder by implementing the Next-Images library. Despite following the setup instructions in the documentation and watching various tutorials online, I am unable to load anything other ...

Triggering multiple subscription functions in Ionic 3 NGRX when a single state change occurs

I have developed an Ionic 3 application that utilizes NGRX for state management purposes. The app is designed to connect to a device via BLE technology. Within my connection page, where the BLE device is connected, I have implemented the following code: ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

Tips for personalizing the ngx-bootstrap datepicker

I am looking to enhance the ngx-bootstrap datepicker popup by adding a link or button within the calendar to select dates with a single click. I have been exploring ways to customize the datepicker without success. Currently, my project is built using Angu ...

Implementing a dependent <select> within an HTML table is a useful feature to enhance user experience and organization of

I have set up a table with editable columns where values can be selected from a drop-down menu. I achieved this by using HTML select. The options in the 'Category tier 2' column are based on the selection made in the 'Category tier 1' c ...

Error: Angular 2 - Node - gulp | Unable to locate module .component

I'm in the process of developing a complete TypeScript application with Node.js in TypeScript that is intended to be used with Angular 2 and built using Gulp as the build tool. The Gulp task successfully compiles all files from /src to /dist, convert ...

Ways to initiate a language shift in the **JavaScript yearly calendar** when the language is modified in an Angular application

1. I have incorporated ngx-translate into my Angular application for translation purposes. 2. I have successfully implemented the ability to switch languages during initialization by specifying options like {language:'ja'} for Japanese within th ...

How can I make ngFor update after an object has been modified?

I'm currently working on a function that updates an object property after an item is dropped in a drag and drop scenario. However, it seems like either my function is incorrect or there might be something else that needs to be done because the display ...

Enabling external POST requests on Angular 4 with asp.net MVC

We are facing a challenge with our Angular 4 app that uses asp.net mvc. The issue arises when an external site, specifically the DIBS payment portal, attempts to redirect back to our page using a POST method, resulting in a 404 not found error. Although th ...

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

In Angular and Typescript, adjusting the index in one dropdown will automatically update the selected option in another dropdown

I'm a newcomer to Angular and I could use some assistance with the following requirement: In my Angular template, I have two dropdowns. I want the selection in one dropdown to automatically reflect in the other dropdown. Both dropdowns pull their val ...

In TypeScript, the catch block does not get triggered

I created a custom pipe in Angular that is supposed to format passed parameters to date format. The pipe contains a try-catch block to handle any errors, but surprisingly the catch block never seems to be executed even when an invalid date is passed. impo ...