Troubleshooting Angular Value Setting without Data DisplayWhen attempting to set a value

When I click the onPrint button, I expect to see the information of a person displayed in the print preview. However, currently, it is not showing up as expected.

Check out the code on CodeSandbox here.

  onPrint(list: any) {
    this.selectedInfo = list;
    print();
  }


<div *ngFor="let list of lists; trackBy: trackByFn">
  <td>
    {{ list.name }} -
    <button type="button" (click)="onPrint(list)">Print</button>
  </td>
</div>

<div id="printSection">
  <h1>SAMPLE HEADER TITLE</h1>
  <div>{{ selectedInfo.name }}</div>
  <div>{{ selectedInfo.description }}</div>
</div>

Answer №1

Recently Updated:

The original poster has made changes to the question by removing reactive form as mentioned in their comment on my answer. Due to this latest modification, a timeout is now required because the print() function executes before the UI element is rendered. By using setTimeout(), a delay is introduced allowing the UI elements to be added.

onPrint(list: any) {
    this.selectedInfo = list;
    setTimeout(() => { print() }, 1000);
}

View the updated code on Stackblitz: https://codesandbox.io/s/hardcore-https-dch04h

Original Response:

A discrepancy was found in the form names (displayForm in component and printForm in HTML) along with some coding issues in your Stackblitz project. I have rectified most of the problems for you.

Additionally, I suggest splitting your form so that each field corresponds directly to a field in the list, which will make it easier to manage them individually.

For detailed changes, refer to: https://codesandbox.io/s/crazy-bassi-e6042s

app.component.ts:

constructor(private formBuilder: FormBuilder) {
    this.displayForm = this.formBuilder.group({
      name: ["", Validators.required],
      desc: ["", Validators.required]
    });
  }

  onPrint(list: { name: string; description: string }) {
    console.log(list);
    this.displayForm.controls.name.setValue(list.name);
    this.displayForm.controls.desc.setValue(list.description);
    console.log(this.displayForm.controls.name.value);
    console.log(this.displayForm.controls.desc.value);
    print();
  }

app.component.html:

<div id="printSection">
  <form [formGroup]="displayForm">
    <h1>SAMPLE HEADER TITLE</h1>
    <div>{{ displayForm?.controls?.name?.value }}</div>
    <div>{{ displayForm?.controls?.desc?.value }}</div>
  </form>
</div>

Answer №2

The issue lies in the fact that the content you are attempting to print is not fully rendered yet. It's crucial to wait before printing the screen and ensure a formgroup is created when assigning an object to a form control.

You may find using the setTimeout() function helpful in this situation. Take a look at an example here

onPrint(list: {}) {
    this.displayForm.get('info').setValue(list);
     setTimeout(() => {
            print();
    }, 50);
  }

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

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Ways to resolve the issue of incompatible parameters 'action' types in JavaScript

I'm encountering a common problem, but I can't figure out why this error is happening. After updating redux, I encountered the following error message: TS2322: Type '(state: ILanguage | undefined, action: PayloadAction<ILanguage>) =&g ...

Optimal Approaches for Conditional Rendering When Button Click is Involved in Combined Server and Client Components in Next.js 14

I'm currently working on a project using Next.js 14 and I've encountered an issue with implementing conditional rendering. In my setup, I have a server component that encompasses both server and client child components. Specifically, one of the c ...

Ways to turn off automatic opening of Google login prompt

I have integrated the abacritt/angularx-social-login package into my project. After injecting SocialAuthService into my constructor, Google signup functionality is automatically displayed on the frontend. Is there a way to prevent this behavior and inste ...

AngularTS regex that enforces the use of a decimal point in numbers

I am working on a requirement where the input should only accept decimal characters, negative or positive. I need to use regex to make the decimal point mandatory, however it is currently allowing negative whole numbers which is not the desired behavior. I ...

Utilizing symbols as a keyof type: A simple guide

Let's consider the following: type Bar = keyof Collection<string> In this scenario, Bar denotes the type of keys present in the Collection object, such as insert or remove: const x: Bar = 'insert'; ✅ But wait, the Collection also c ...

How can you simulate a node-cron job using jest?

I am currently working on a node application that is built with Typescript and includes a cron job. The cron job is triggered when the server starts. I have been writing unit tests for this application, but I am facing difficulties in mocking the node-cro ...

The function passed as a prop is unrecognized

I am having an issue with passing the function toggle and it is showing as undefined. Any advice on how to resolve this? function page() { const [open, setOpen] = React.useState(false); const handleToggle = () => { setOpen(!open); }; ...

Customize time formatting in Angular to accommodate localized time formats

I am utilizing Angular's localization service version 8.3.28 to support English, Spanish (Mexico) with code es-MX, and Spanish (Spain) with code es-SP While using the date pipe: {{ foo.Date | date: 'shortDate' }} The dates are changing to ...

The route information is not appearing on the screen

I am facing an issue with my application's route called home. The content on this route is not being displayed; instead, only the menu from app.component is shown. I believe I might be overlooking something obvious. Can someone assist me with this pro ...

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

Utilize the TypeScript Compiler API to extract the Type Alias Declaration Node from a Type Reference Node

Currently, I am utilizing ts-morph library which makes use of the TS Compiler API. Here is an example of my code: export type Foo = string export const foo: Foo = 'bar' Whenever I try to find the type for the export of foo, it returns string. H ...

Mat-stepper in Angular Material causing binding errors

Trying to bind the parent mat-stepper component in order to check if the selected index is something, then do something else. It works but gives errors for each tab that is bound. The error message says it can't find property '0' of undefine ...

Optimizing my AngularJS bundle is pushing me towards upgrading to Angular 5

Regarding my AngularJS application, it was initially created using 'yo angular-fullstack' with JS scripting instead of TS. It is functional but experiencing performance and user experience issues. The deployment is on AWS ElasticBeanstalk nano i ...

The error message "Invalid export value for Next.js with TypeScript: 'getStaticProps'" indicates a problem with the entry export value

I'm currently diving into the world of Next.js and Typescript, and I've run into an error that has left me stumped as there doesn't seem to be much information available on it: "getStaticProps" is not a valid Next.js entry export value.ts( ...

Angular has the feature to postpone, halt, and resume right from where it left

As I delve into the world of Angular, I am trying to create a scenario where messages are displayed with a delay and the ability to pause for a response based on the message. While I have managed to display the messages, implementing the functionality to ...

Type returned by a React component

I am currently using a basic context provider export function CustomStepsProvider ({ children, ...props }: React.PropsWithChildren<CustomStepsProps>) => { return <Steps.Provider value={props}> {typeof children === 'function&ap ...

What is the best way to programmatically click on an element within the body of a webpage from an Angular component?

I am running a crisp chat service on my website and I am attempting to interact with the chat box from one of my component's typescript files. The chat box is represented as a div element with the id crisp-client inside the body tag. Can someone plea ...

Guide on entering text into an Angular input field with Selenium in Python after navigating tabs

After switching tabs, I am attempting to enter text into an Angular input field. However, I keep encountering the following errors: AttributeError: 'tuple' object has no attribute 'send_keys' or ElementClickInterceptedException or NoS ...

Prevent special characters from being entered into an HTML input box with Angular 7

I'm looking to limit the use of special characters in an HTML input box using Angular 7. I also need to set requirements for only allowing numbers, letters, etc. As I am new to Angular, any assistance would be greatly appreciated. I've attempte ...