Utilizing conditional binding with ngModel in Angular 5

In my Angular 5 project, I am facing some issues. I have two models called Person and Employee where Employee inherits from Person and has its own attributes. In the HTML file of my component, I created a form with several input fields:

<input type="text" name="name" [(ngModel)]="person.name" />
<input type="text" name="numberPhone" [(ngModel)]="person.numberPhone" />
<button (click)="isEmployee=true" type="button">Is employee</button>
<div *ngIf="isEmployee">
<input type="text" name="salary" [(ngModel)]="employee.salary" />
</div>

The issue arises when I try to use the same form to bind person if isEmployee is false or employee if isEmployee is true. The following code snippet does not yield the desired result:

[(ngMode)]="isEmployee ? person.name : employee.name"
[(ngMode)]="isEmployee ? person.numberPhone : employee.numberPhone "

Is there a way to achieve this without repeating the HTML code?

Answer №1

Have you considered creating a shared template with an ngModel binding like this:

[(ngMode)]="user.name"

This way, you can use the same template file across different components based on the type of user (for example, one component for person and another for employee). Simply set user to employee in the employee component and person in the person component.

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

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

A guide on efficiently storing and retrieving a webpage containing two angular2 components using local storage

I've been attempting to store and retrieve a page containing two angular2 components from local storage using the following code, but the component CSS is not being applied. Here is the code I'm using to save: localStorage.setItem('pageCon ...

best practice for updating a node in ng-zorro-antd tree

I'm attempting to make changes to the node titles in a tree structure. I have learned that the tree will only show these updates if the nodes array is changed by reference (as shown in the example). However, when I update the nodes, the tree flickers ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

Struggling to containerize an Angular application

Struggling to deploy my Angular application as a docker image on Azure, I have hit a roadblock. Following the steps outlined in a video tutorial at https://learn.microsoft.com/en-us/azure/developer/javascript/tutorial-vscode-docker-node-01?tabs=bash did no ...

Show the attribute of an element in a pop-up window

I have a modal from ngx-bootstrap that I want to display in there a property of my object let's say the name: public students = [ { id: 1, name: 'lorem'} In this button that is common for all entries in the table (each row has this butt ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

Alert message will be displayed upon clicking on stepper titles in Angular 10

I need to implement an alert when the user clicks on the second stepper labeled 'Fill out your address'. In addition to displaying a red border around the empty form field, I also want to show an alert message. I have already set up a function ca ...

Avoid obtaining cookies within the TRPC environment

Recently, I've been setting up TRPC with Next.js and attempting to implement server-side rendering where I fetch user data before the page loads using the trpc.useQuery hook. However, I'm facing an issue where I cannot access the JWT token cookie ...

Issue found in ng-bootstrap.js ng-bootstrap for Angular 6

Recently, I added ng-bootstrap to my Angular project and included its modules. However, upon checking the CLI, an error was displayed. "WARNING in ./node_modules/@ng-bootstrap/ng-bootstrap/fesm5/ng-bootstrap.js 9853:57-75 "export 'ɵɵdefineInj ...

Is there an external class available to integrate with my interface?

Is there a method to establish an external class (part of an NPM module) as a class that adheres to a specific interface? Consider the following scenario: import {someClass} from "someNPMmodule"; interface myInterface { foo: () => void } I am now ...

Trouble installing Angular: ENOENT Error causing issues

Currently in the process of setting up angular. I have been diligently following the provided installation instructions, but when executing npm install -g @angular/cli, I encounter the error shown in the screenshot below. https://i.sstatic.net/LSP7R.jpg H ...

The compatibility issue between Bootstrap and Angular 2 is causing some challenges

Hey there, I recently enrolled in an Angular 2 course on udemy and everything was running smoothly until I encountered an issue while trying to install bootstrap. I followed the installation steps diligently, but whenever I attempt to add any bootstrap el ...

Activate the mat-menu within a child component using the parent component

Incorporating angular 6 along with angular-material, I am striving to trigger the matMenu by right-clicking in order to utilize it as a context menu. The present structure of my code is as follows. <span #contextMenuTrigger [matMenuTriggerFor]="context ...

Collaborative service utilization in Angular 2

My goal is to create a shared service for my app. import { Injectable } from '@angular/core'; @Injectable() export class SharedService { testService() { console.log('share!'); } } However, when I attempt to inject this shared ...

Guide on navigating to a different page using a function with router link in Angular using TypeScript

Trying my hand at Angualar and Typescript for the first time. I am working on creating a login page where users can move to another page if their credentials are correct. To achieve this, I want to use a function that is triggered by clicking a button. How ...

Filter and transfer data from one Angular array to another

As a newcomer to Angular, I am working with an array of events containing multiple arguments. My goal is to filter these events and separate them into two new arrays: upcoming events and past events. Below is a snippet of the TypeScript code I am using: a ...

Struggling to run my Pact tests using Karma and Angular

I'm struggling to run pact tests with Karma in my Angular app setup. Below is the relevant snippet from my package.json. "@angular/core": "~13.3.6", "@pact-foundation/karma-pact": "^3.1.0", "@pact-foundatio ...

Ionic 2 faced an unresolved core-js dependency issue

Recently, I started working on a new Ionic 2 project and encountered an issue when trying to incorporate https://github.com/afrad/angular2-websocket. Upon installation, I received the warning message: UNMET PEER DEPENDENCY core-js@^2.4.1 The template pro ...

Steps for displaying the appended string on a web page using React hooks

Check out this code snippet: const Gauge = (props) => { const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = (max + 1) / points; const realPeaks = peaks.map((peak) => Math.floor(p ...