简体   繁体   中英

How to pass property from parent to child component in Angular 8?

I have an array of DossierEntry and if you select one item that you have to go to that item. But if you now select a item you will get an error like this:

dossier-correspondence-item.component.html:15 ERROR TypeError: Cannot read property 'isJson' of undefined at Object.updateDirectives (dossier-correspondence-item.component.html:15) at Object.debugUpdateDirectives [as updateDirectives] (core.js:30537) at checkAndUpdateView (core.js:29933) at callViewAction (core.js:30174) at execEmbeddedViewsAction (core.js:30137) at checkAndUpdateView (core.js:29934) at callViewAction (core.js:30174) at execComponentViewsAction (core.js:30116) at checkAndUpdateView (core.js:29939) at callViewAction (core.js:30174)

and the line is this:

    <div *ngIf="!item.isJson; else summaryIsJson" class="correspondence-item-text correspondence-item-iframe-container">

The Parent component with the array looks like this:

<ng-container *ngIf="correspondenceEntries">
    <app-dossier-correspondence-list [correspondenceEntries]="correspondenceEntries" (onClick)="gotoItem($event)"> </app-dossier-correspondence-list>
  </ng-container>

  <ng-container *ngIf="attachmentEntries">
    <app-dossier-correspondence-attachments
      [attachmentEntries]="attachmentEntries" (onClick) = "gotoItem($event)"
    ></app-dossier-correspondence-attachments>
  </ng-container>

  <app-dossier-correspondence-item
  [item]="single"
  (goBack)="goBack($event)"
  *ngIf="showingSingle">
  </app-dossier-correspondence-item>
</app-vital10-page>

and the ts code of the piece of code what important is of Parent component:

gotoItem(index, type: string) {
   
    switch (type) {
      case 'correspondence': {
        console.log('triggered');
        this.single = this.correspondenceEntries[index];

        break;
      }
      case 'attachments': {
        this.single = this.attachmentEntries[index];
        break;
      }
      default: {
        break;
      }
    }
    this.showingSingle = true;
  }

The model of DossierEntry looks like this:

export class DossierEntry {
  dossierEntryId: number;
  date: string;
  name: string;
  referenceId: string;
  summary: string;
  jsonSummary: Array<DossierEntryHeader>;
  isJson: boolean;
  hasFile: boolean;
  file: Blob;
  fileName: string;
  type: string;
}

So my question is what I have to change?

Thank you

So this is in the Parent component:

<ng-container *ngIf="correspondenceEntries">
    <app-dossier-correspondence-list [correspondenceEntries]="correspondenceEntries" (onClick)="gotoItem($event)"> </app-dossier-correspondence-list>
  </ng-container>

  <ng-container *ngIf="attachmentEntries">
    <app-dossier-correspondence-attachments
      [attachmentEntries]="attachmentEntries" (onClick) = "gotoItem($event)"
    ></app-dossier-correspondence-attachments>
  </ng-container>

And this is the child component:

<div *ngIf="!showingSingle  && correspondenceEntries && correspondenceEntries.length > 0;">
  <div class="main-row main-row-dossier">
    <section class="data-entry">
      <h3 class="dossier-header">Algemeen</h3>
      <table class="dossier-table" *ngIf="correspondenceEntries  else loadingCorrespondenceEntires ">
        <thead class="dossier-tableheader">
          <tr>
            <th class="dossier-tablehead fixed-one-fifth">Datum</th>
            <th class="dossier-tablehead fixed-four-fifths">Onderwerp</th>
          </tr>
        </thead>
        <tbody class="dossier-tablebody">
          <tr class="dossier-correspondencerow" *ngFor="let entry of correspondenceEntries; let i = index" (click)="click(i, entry.type)">
            <td>{{ entry.date | date:"dd-MM-y" }}</td>
            <td>{{ entry.name }}</td>
          </tr>
        </tbody>
      </table>
    </section>
  </div>
</div>

<ng-template #loadingCorrespondenceEntires>
  <div>..Loading </div>
</ng-template>



and ts file:


export class DossierCorrespondenceListComponent implements OnInit {

  @Input()
  correspondenceEntries: DossierEntry[];


  @Output() onClick = new EventEmitter();

  @Input() showingSingle;

  constructor() { }

  ngOnInit() {
  }

  // tslint:disable-next-line: use-life-cycle-interface
    ngOnChanges(changes) {
  }

  click(i, type) {
    this.onClick.emit({i: i, type: type});
  }


}

And I have it already declared in parent component like this:

export class DossierCorrespondenceComponent implements OnInit {
  correspondenceEntries$: Observable<DossierEntry[]>;
  attachmentEntries$: Observable<DossierEntry[]>;

  @Input() allCorrespondence: Array<DossierEntry>;
  @Input() correspondenceEntries: Array<DossierEntry>;
  @Input() attachmentEntries: Array<DossierEntry>;

  //@Input() myGotoItem: Function;

  message = '';
  emptyMessageCorrespondentie = 'Geen correspondentie.';
  errorMessageConnection = 'Er ging iets mis met de connectie. Probeer over enkele minuten nogmaals.';

  correspondenceLoaded = false;

  showingSingle = false;

   single: DossierEntry;

oke, And If I do this:

 <ng-container *ngIf="correspondenceEntries">
    <app-dossier-correspondence-list [correspondenceEntries]="correspondenceEntries" (click)="gotoItem(i, entry.type)"> </app-dossier-correspondence-list>
  </ng-container>

I get this error:

ERROR TypeError: Cannot read property 'type' of undefined

But if I do this:

  click(i, type) {
    console.log('clicked ' + type);
    this.onClick.emit({i: i, type: type});
  }

I see: clicked correspondence

and so this is the DossierCorrespondenceItemComponent:

export class DossierCorrespondenceItemComponent implements OnInit {
  @Input() item: DossierEntry;

  @Output() goBack = new EventEmitter();

  safeHTMLUrl: SafeResourceUrl;
  fileLoading = false;
  showFile = false;
  canOpenBlob = false;

  constructor(
    public sanitizer: DomSanitizer,
    private router: Router  ) {
    // IE/Edge specific
    this.canOpenBlob = !!window.navigator && !!window.navigator.msSaveOrOpenBlob;
  }

  handleGoBack() {
    this.goBack.emit();
  }
  openPdf(dossierEntryId: number) {
    this.router.navigate(['dossier/overig/pdf/', dossierEntryId]);
  }

  ngOnInit() {
    if (!this.item.isJson) {
      if (window.btoa) {
        this.safeHTMLUrl = this.sanitizer.bypassSecurityTrustResourceUrl(
          'data:text/html;base64,' + btoa(this.item.summary)
        );
      } else {
        this.safeHTMLUrl = this.sanitizer.bypassSecurityTrustResourceUrl('data:text/html;utf-8,' + this.item.summary);
      }
    }
  }

and this is the error:

Cannot read property 'isJson' of undefined
    at DossierCorrespondenceItemComponent.push../src/app/dossier/dossier-correspondence-item/dossier-correspondence-item.component.ts.DossierCorrespondenceItemComponent.ngOnInit (dossier-correspondence-item.component.ts:36)

You should store your selected entry somewhere in your parent component

selectedEntry: DossierEntry;
selectEntry(entry: DossierEntry): void {
   this.selectedEntry= entry;
}

Also, you should use (click) event instead of (onClick) in angular. Use the selectEntry method on click.

And your call to child component should have an @Input (see https://angular.io/guide/component-interaction )

When calling child component, check nullability of your selectedEntry, and you'll be fine for the error you're having

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM