Using ngModel with a dynamic variable

Having a issue with using ngModel to pass a value to bump object property retrieved from the bumpDetail.name array.

I've included my code snippet below.
Can someone please review it and point out where I've made a mistake? Thank you.

<p *ngFor="let bumpDetail of bumpDetail">
    <input type="checkbox" id="device" [(ngModel)]={{bump.bumpDetail.name}}/>
    <label for="device">{{bumpDetail.name}}</label>
</p>
 Bump[] = [{
"name": "bump_1",
"status": true
}, {
"name": "bump_2",
"status": false
 }, {
"name": "bump_3",
"status": true
}]

There seems to be an error here.

Parser Error: Got interpolation ({{}}) where expression was expected at column 0 in [{{bumpDetail.name}}] in ng:///AppModule/SettingComponent.html@129:59 ("p *ngFor="let bumpDetail of bumpDetail">

Answer №1

[] and {{}} are always kept separate. Choose between the two options.

[(ngModel)]="this[bumpDetail.name]"

{{}} should only be used for string interpolation.

Answer №2

An issue has been identified in [(ngModel)]={{bumpDetail.name}}

The correct syntax should be: [(ngModel)]="bumpDetail.status"

It's unnecessary to use {{}} when utilizing [(ngModel)] or any other ng-directive.

Additionally, there appears to be an error here

<p *ngFor="let bumpDetail of bumpDetail">
Make sure the variable name is accurate, as they cannot be the same.

I suggest updating it to:

<p *ngFor="let bumpDetail of bumpDetailArray">
where bumpDetailArray represents the array

Answer №3

Beginning with the fundamentals is crucial. "{{}}" signifies an expression, while [(ngModel)] is utilized for two-way binding where () represents emitting and [] signifies binding. To correctly implement this, you should use [(ngModel)]="bumpDetail.name" for binding and {{bumpDetail.name}} for expression printing. Attempting to combine both as demonstrated above is not permissible.

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

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Doughnut Chart with Color Gradients in ng2-charts

Currently, I am exploring the world of Chart.js and ng2-Charts within Angular. Specifically, I am experimenting with Doughnut Charts and have a desire to create a Multi Level Chart. However, I am facing an issue where I am unable to customize the colors fo ...

React hook triggering re-render

A function has been implemented to retrieve and decode user claims from a token stored in local storage using a hook. export const useActiveUser = (): { user: IUserTokenClaims | null } => { const [user, setUser] = useState<IUserTokenClaims | nul ...

Protecting scripts using bypassSecurityTrustStyle in Angular

Is there a way to remove all script tags from a string while preserving the style? Consider this code snippet where we sanitize the style of a string: getSanitized(s: string) { const safeStyle: any = this.sanitizer.bypassSecurityTrustStyle(s); re ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

I am looking to fetch a zip file within the MEAN stack framework

Here is frontend code (Angular):- download(user) { this.clientAPI.get(Endpoints.DOWNLOAD).toPromise() .then(res => { let blob = new Blob([new Uint8Array(res.file)], { type: 'application/zip' }); console.l ...

Is it possible to determine the type of a variable by simply clicking on it in IntelliJ (specifically in typescript)?

Having the ability to hover over a variable and see the expected type in TypeScript would be incredibly beneficial. I'm curious if there is some sort of internal static analysis being conducted that stores this information. Is there a method for acces ...

execute a function once an asynchronous function has finished running

I have observed the practice of calling functions in succession using promises, and I have an async function with observables. fetchData() { this.generatePayload() this.dataService .getData(this.payload) .subscribe( (data: any ...

Angular tutorial: Changing website language with translation features

Looking to translate my existing Russian website into another language using angular localization. Any recommendations on where I can find resources or tutorials for this? ...

How to properly integrate Bootstrap with Angular 2?

Currently developing an angular2 app and contemplating whether to include bootstrap reference on the component level or in the index.html file. Interested to learn about the advantages and disadvantages of each approach. Thank you! ...

How can I incorporate an interface and specify a particular type as the return value in TypeScript?

interface Inter{ str:string } function func(){ let v:Inter={ str:'abc' }; return v; } func()//Is there a way to ensure that the type of value returned from `func` is {str:'abc'} without explicitly declaring it i ...

What is the correct way to interpret a JSON file using TypeScript?

Encountering Error Error TS2732: Cannot locate module '../service-account.json'. It is suggested to use the '--resolveJsonModule' flag when importing a module with a '.json' extension. import serviceAccountPlay from '../ ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

Why does the custom method only trigger once with the addEventListener?

I am attempting to connect the "oninput" event of an input range element to a custom method defined in a corresponding typescript file. Here is the HTML element: <input type="range" id='motivation-grade' value="3" min="1" max="5"> This i ...

Sign up for a feature that provides an observable exclusively within an if statement

There is an if clause in my code that checks for the presence of the cordova object in the window global object. If cordova is present, it will make a http request and return the default angular 2 http observable. If the application is in a web context wh ...

Steps for utilizing response data as parameters for useInfiniteQueryHere is how you can make

On the specific page where I am implementing useInfiniteQuery const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery( ['posts', searchState], ({ pageParam = 1 }) => post.search({ . ...

Displaying a random element from the state array in React Native

I'm attempting to display a random item from the state array, with the possibility of it changing each time the page reloads. Here's what I have tried so far, any suggestions or ideas are welcome! This is my current state: state = { randomIt ...

Struggling to add phantom-js to my Angular project

I'm looking to incorporate the phantomJS library into my Angular 4 project for continuous integration with Jenkins. No matter what method I try, I keep encountering the same (or similar) error. For instance, when following this tutorial and attemptin ...