Sending an array of Json data to a specific directive in Angular 5

Trying to work with angular 5 and faced with a challenge: how can I pass a JSON array to a custom directive?

Here's my current code:

product.ts

products=[{"laptop":"dell", id:1}, {"laptop":"lenovo", id:2}];

product.html

<div product-data="{{data}}" *ngFor="let data of products"></div>

product-data.ts

@Directive({
  selector: '[product-data]'
})
export class ProductDetailsDirective {
    @Input('template-thumbnail') productSelected:any;

    ngAfterViewInit() {
      console.log(this.productSelected)
    }
}

Upon logging the productSelected, I'm seeing a string [object Object] instead of an array.

Any suggestions or guidance on this issue would be highly appreciated.

Answer №1

Give this a shot

<section [item-info]="info" *ngFor="let info of items"></section>

Answer №2

If you define

@Input('template-thumbnail') productChosen:any[];
(this will treat it as a string) as
@Input('template-thumbnail') productChosen:any[];
, that specifies it as an array type.

Alternatively

You have the option to utilize JSON.parse in order to convert the string into an array.

JSON.parse(this.productChosen)

Answer №3

Consider implementing the following pipe function

<div product-info="{{data | json}}" *ngFor="let data of products"></div>

I have not tested this yet. If your directive receives data as a string, you can simply use JSON.parse to convert it back to an object.

Alternatively, you can utilize JSON.stringify and JSON.parse methods. Below is an example of how you can apply them in your scenario.

product.html

 <div product-info="convertData(data)" *ngFor="let data of products"></div>

product.ts

products=[{"laptop":"dell", id:1}, {"laptop":"lenovo", id:2}];

convertData(data){ 
  return JSON.stringify(data)
}

product-data.ts

Within your directive class, utilize the parse function to revert it back to a JSON Object using JSON.parse()

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

Utilizing NgModelGroup nesting in various components for improved data management

Whenever I attempt to nest NgModelGroup inside another NgModelGroup, Angular seems to just ignore it. I'm currently utilizing Angular 12 and Template-driven Forms. Here is how my code appears: app.component.html <form #form="ngForm"> ...

Error TS2339: The 'selectpicker' property is not found on the 'JQuery<HTMLElement>' type

Recently, I integrated the amazing bootstrap-select Successfully imported bootstrap-select into my project with the following: <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstra ...

Redirecting with Angular2 from a static function

Hello, I currently have a 'static class' called Utils which contains only static methods (helpers): export class Utils { static doSomethingAndRedirect() { ...do something... redirectTo->'/home' } } I am ...

What is the method for accessing the HTML of the ElementFinder directly in the debugger without using a promise?

Upon analyzing the situation, I've come across an element named this.page.taskAssignment which is categorized as an ElementFinder. During my UI tests, when I attempt to click on this element, there seems to be no response. It has led me to believe tha ...

Can a concept like "A Rectangle can be a Square but a Square cannot be a Rectangle" be formulated?

Currently, I am working on developing a unique "loose" nominal type that allows assignment from its base type, but restricts assignment from other nominal types with the same base type. Is there a way to modify the existing Nominal type found here to achie ...

error TS2339: The attribute 'properties' is not accessible on the class 'TestPage'

Utilizing a typescript abstract class as the base class of my layout component in React has been essential for my project. The implementation of this base class looks something like this: import { IPageLayoutActions, IPageLayoutLocalState, IPageLayoutProp ...

I find myself stuck in one component in Angular routing, unable to navigate away from the current URL

After developing a function that retrieves the value of an item and redirects to a different component based on certain logic, here is the code snippet: navigate_to_page(url) { console.log(url) console.log(['../' + url]) th ...

Is it possible to detect changes in the p-columnFilter match options and trigger a function in Angular and PrimeNG?

Is there a way to attach a function that triggers every time the user selects an option from the matchOption of p-columnFilter. <p-columnFilter type="date"> ... </p-columnFilter> https://i.sstatic.net/LHPa4.png For example, you can ...

Show basic HTML elements on a single page of an Angular Material web application

I am working on an Angular (6) web app with a customized theme using Angular Material. Currently, I am trying to incorporate a popup dialog that includes basic HTML elements like checkboxes, buttons, and inputs. Even though I have successfully displayed ...

Using the forEach method in Angular 2 the directive loop

Currently, I am tackling a project utilizing Angular 2. In one specific scenario, I receive an Array from an API call. The structure of the Array is as follows: [{'key1': 'value1', 'key2': 'value2', 'key3&apos ...

Guide to loading CSS and fonts directly for jHipster 7

After realizing that my project is loading CSS and fonts online, I encountered an issue where the project appears without any styling when my laptop is offline. Despite searching for ways to load CSS locally, there doesn't seem to be much documentatio ...

Dealing with API Errors in Ngrx

I came across an interesting scenario in the ngrx example-app provided on Github. When starting a new project, I always strive to follow the best practices, so I referred to the example app for guidance. In one particular instance within the application, t ...

What is the best way to automatically focus on my input when the page loads?

My Angular application has a 'slider' component that loads 3 child components utilizing ng-content. The first child component contains a form, and I am trying to focus on the first field upon page load. Despite setting up ViewChild correctly to r ...

Ways to implement intervals within the ngOnInit method

I am looking to implement a ticking feature in my app. My initial approach was to use the interval function and subscribe to it within the ngOnInit lifecycle hook. However, following this method results in the app loading indefinitely until the interval c ...

Ensuring a Markdown editor is not left empty in a form to prevent errors

Recently, I integrated a markdown editor into my angular HTML form like so: <td-text-editor class="full-width" formControlName="description"></td-text-editor> I want to ensure that if the description field is left empty in the form, a ...

Is it possible to prevent the Virtual Keyboard from automatically appearing on mobile devices?

Whenever a user enters a number on a page component, the Virtual Keyboard on their Mobile device pops up and shifts the entire page. I am looking for a solution to either disable the on-screen keyboard or ensure that the text box remains visible even when ...

Implementing Immer in Typescript

Recently, I've been exploring the possibility of integrating Immer into my React project that already utilizes Typescript. Unfortunately, I haven't been able to discover a clear guide on how to effectively employ Immer in conjunction with Typescr ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

Error in Angular 13: Struggling to remove the likelihood of an object being null

I am working on a piece of code that includes the following: var item = document.getElementById("div0"); item.parentNode.removeChild(item); // The error seems to be here Every time I run this code, I encounter the error message: object is p ...

How can I customize the date format in the ng-pick-date picker?

I need help setting the date format for a pick-date picker. I have been struggling to figure out how to do it. Can anyone provide me with an example of how to set the date format? Below is the code for my date picker: <label class="control-label my-la ...