Home > Mobile >  Not Displaying Data When Setting Value in Angular
Not Displaying Data When Setting Value in Angular

Time:06-13

I wanted to display the info of a person when I try to click the onPrint button. Right now, it just doesn't display on the print preview.

codesandbox

  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>

CodePudding user response:

The problem is that the content you are trying to print is not rendered. Before you print the screen you need to wait. Also while assigning object to form control you should create a formgroup first. I think setTimeout() function will help you..

You can see example here

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

CodePudding user response:

Updated:

The OP has changed the question, and removed reactive form from the question (per his comment in my answer). With the latest change, it requires a timeout, since the print() function executing, before the UI element is getting rendered. The setTimeout() will add some delay and allow the rendered to add the UI elements.

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

Stackblitz: https://codesandbox.io/s/hardcore-https-dch04h

Original:

There's mismatching form name (displayForm in component, but printForm in html) and some coding issue in your Stackblitz. I have cleaned up most of it.

Also, I think it's better if you split your form to have one to one mapping the form and list fields. Makes it easier to work with each of them.

Full change available here: 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>
  • Related