mmcc88
mmcc88

Reputation: 176

Template from parent to child component doesn't re-render

I got a modal wrapper component (child.component) that uses the template from parent (parent.component).

But the variable in the template won't be re-rendered even the someFunction() is triggered from within the parent. It just remains as the default value 999 in this case.

How can I make sure the template re-render whenever the parent's variable order is updated?

parent.component.html

<div>parent content</div>

<ng-template #temp> 
  <div>{{ order.Id }}</div>   <!-- THIS DOESN'T RE-RENDER -->
</ng-template>

<app-modal-wrapper [temp]="temp"></app-modal-wrapper>

parent.component.ts

export class ParentComponent implements OnInit {

  public order: any = { Id: 999 }; 

  public someFunction(x) {
    this.order = { Id: x };
  }
}

child.component.html

<ng-container [ngTemplateOutlet]="temp"></ng-container>

child.component.ts

@Component({
  selector: 'app-modal-wrapper',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  @Input() temp: TemplateRef<any>;
}

note. I refer to this guide to pass template from parent to child component: https://medium.com/geekculture/angular-3-ways-you-can-pass-templates-from-parent-to-child-components-to-promote-reusability-ba0a0bfb77c6

Upvotes: 0

Views: 88

Answers (1)

tlvi38
tlvi38

Reputation: 311

Use ng content instead of an input with ng-template. It seems way more appropriate.

ChildComponent.html =>

<ng-content></ng-content>

ParentComponent.html =>

<div>parent content</div>

<app-modal-wrapper><div>{{ order.Id }}</div></app-modal-wrapper>

Upvotes: 0

Related Questions