Richard Turner
Richard Turner

Reputation: 441

Nesting components in Angular 12 - issue with 'Scope'

just trying to get my head around Angular12 after years on AngularJS and am having what I hope is a simple to fix problem: I know that Scope is no longer but it appears that the component is rendering data from a different scope.

I have a component that gets some results from a service and displays them on the page.

<app-search-component> This has a method called doSearch(xxxx) that populates this.items and then renders the result.

If I route to that component directly it all works perfectly.

What I am trying to active is to use that componet in a similar way to a directive in angular JS

I have tried passing the component via the constructor & tried creating a new component within my component but I cannot get the child component to refresh its view.

It seems that when debugging the child component has a different 'scope' to the version on my template.

Template example My Parent Component

  <form [formGroup] ="searchForm" class="searchForm" (ngSubmit)="onSubmit()">
      <mat-form-field class="search-full-width" appearance="fill">
        <mat-label>User Name</mat-label>
        <input matInput value="" formControlName="name">
      </mat-form-field>
    
      <mat-form-field class="search-full-width" appearance="fill">
        <mat-label>Email</mat-label>
        <input matInput formControlName="email">
       
      </mat-form-field> 
      <mat-form-field class="search-full-width" appearance="fill">
        <mat-label>Postcode</mat-label>
        <input matInput formControlName="postcode">
       
      </mat-form-field>
    
      <button mat-raised-button color="primary" type = "submit">Search</button>
</form> 
<app-search-component>

My parent component contains a call to the search method as follows:

Constructor:

this.searchComp= new MySearchComponent(_myService, _zone);

On Submit

 this.searchComp.doSearch(this.searchText);

Upvotes: 0

Views: 182

Answers (1)

you have 2 options here. you can have the search be done via a service or you can use viewchild for this. to make the code seem more like you already have you can do something like this in your parent component

@ViewChild(MySearchComponent)
searchComp : MySearchComponent

the template will create the component for you so remove the new MySearchComponent from your constructor

Upvotes: 1

Related Questions