Guide to creating a setter for an array property in Angular 2 (Typescript) that will be filled by the view

Question:

private _secretQuestions: {question: number, answer: string}[];

Within my HTML, I have three select boxes representing questions, each with a corresponding input box for answers. My goal is to map the selected questions and input values to the _secretQuestions property. To account for the limited number of questions (three), I initialized the array as follows:

private _secretQuestions = [{question: 0, answer: ""}, {question: 0, answer: ""}, {question: 0, answer: ""}];

However, I am struggling to write the setter for this property:

set secretQuestions(value: Array<{question: number, answer: string}>) {
    // what code here?
}

When binding in my HTML,

<select class="form-control" [(ngModel)]="regModel.secretQuestions">
... </select>

triggers the setter, but if I could somehow trigger the setter like:

<select class="form-control" [(ngModel)]="regModel.secretQuestions[0].question">

I believe it would help resolve my issue.

Any suggestions on the correct approach to take?


EDIT

The _securityQuestions property is part of a Provider which is injected into the component. It is essential for the property to be private within the provider.

Answer №1

When using Angular's NgModel directive, there is no need for a setter. You can directly bind to the property like this:

<select class="form-control" [(ngModel)]="regModel.secretQuestions[0].question">`

This allows for two-way binding. If you need to handle a change in the value, you can use the following approach:

<select [ngModel]="regModel.secretQuestions[0].question"
        (ngModelChange)="updateQuestion($event)">

For more information on forms in Angular, you can refer to the official guide at https://angular.io/docs/ts/latest/guide/forms.html and specifically the section on https://angular.io/docs/ts/latest/guide/forms.html#!#inside--ngmodel-

Answer №2

One method to break down the "2-way-binding" aspect is by employing the following technique:

<select class="form-control" [ngModel]="regModel.secretQuestions" 
    (ngModelChange)="secretQuestion = regModel.secretQuestions[0].question">

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

Angular displays the error message TS2339, stating that the property 'handleError' is not found on the 'HeroService' type

Hey everyone, I know there are already a few questions out there about Typescript compilation errors, but I'm facing a unique challenge that I can't quite figure out. I'm currently working on the Angular Tour of Heroes app and trying to com ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...

Provide a parameter for a function's callback

I am attempting to utilize lodash's debounce function to delay the onChange event. See the code snippet below. import React, { useState, useEffect, useCallback } from "react"; import { TopBar } from "@shopify/polaris"; import { debounce } from "lodas ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

Having trouble retrieving data from a behavior subject while using switchMap and refreshing in RxJS

app.component.ts import { Component, OnInit } from '@angular/core'; import { of } from 'rxjs'; import { TestService } from './test.service'; @Component({ selector: 'app-root', templateUrl: './app.component. ...

Why aren't the child elements in my React / Framer Motion animation staggered as expected?

In my finance application, I am creating a balance overview feature. To display the content, I pass props into a single <BalanceEntry> component and then map all entries onto the page. With Framer Motion, my goal is to animate each rendered <Bala ...

Using the 'disabled' parameter in the form state object does not have any effect on the FormControl constructor

We've encountered a similar issue in the past: It seems like the disabled attribute is being used with a reactive form directive. If you initialize this control with the disabled property set to true in your component class, Angular will automatical ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Empty Angular-chart.js Container

How can I resolve the issue of getting a blank div and no output while trying to display a chart where the options, labels, and other data are initialized in the TypeScript controller and then used on the HTML page? I added the angular-chart.js library us ...

Unlocking the Power of Asynchronous Data in Angular's Dynamic Form Patterns

Utilizing the dynamic form pattern in Angular has been incredibly helpful for our team. By defining our controls in ngOnInit, the form is dynamically constructed based on our needs. However, we've encountered a challenge with forms that require initia ...

Exporting the default value from a TypeScript declaration file module

Imagine having a declaration file called foo.d.ts: declare namespace foo { interface Bar { (): void; } } declare var foo: foo.Bar; export default foo; Upon compilation: import Foo from './foo'; Foo(); The result is: "use strict"; va ...

"Troubleshooting: Issues arise with Kendo UI Angular file upload component when dealing with

Currently, I have integrated the Kendo Angular File Upload component into my Angular 7 application. The backend of this application is built using ASP.NET Core 2.1 and hosts a MVC API through Kestrel. While the file uploads for smaller files are successful ...

Problem with npm link <package>

Operating System: Windows 7, 64-bit Npm Version: 3.10.10 Node Version: 6.9.4 Hello, We are currently encountering issues with a custom npm package that we have published on our registry and installed in our Angular applications. Below are the di ...

The inversify middleware is executed a single time

I utilize Inversify for object binding in the following manner: container.applyMiddleware(loggerMiddleware); let module = new ContainerModule((bind: interfaces.Bind) => { bind<Logger>(TYPES.Logger).toConstantValue(logger); bind<ILogger ...

Using Angular to incorporate an attribute directive into an element within index.html

I have included some script tags containing asynchronous JavaScript libraries in my index.html file. I want to apply an attribute directive that will control their "activation" by changing the type attribute from "text/plain" to "text/javascript" once the ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Make sure to include a property that is indexed when typing

I am currently working on defining a type to represent a list (hash) of HTTP headers. This type is supposed to be a hash that only contains key / string pairs: type TStringStringHash = { [key: string]: string } However, the issue I am facing is that i ...

Angular with Leaflet and Leaflet AwesomeMarkers error: "Attempting to access 'icon' property of undefined"

I'm attempting to integrate Leaflet Awesome Markers into my Angular 10 project to incorporate Font Awesome icons in my Leaflet markers. However, I'm running into an error when trying to create a L.AwesomeMarker. https://i.sstatic.net/7o81y.png ...

What is the functionality of .map / .subscribe in Angular2?

I am facing a challenge trying to populate 3 variables (arrays) from Firebase using AngularFire2. The structure of my database looks like this: https://i.sstatic.net/3pDY7.png I am struggling with resolving Promises in order to map and fill those variab ...