Friday, March 3, 2017

Nested component angular 2

For creating nested component we need to create the component under the shared folder.
When we use a component as a directive, we need to tell angular how to find that directive.We do that by declaring the nested component in an angular module as shown below

In the import we need to specify the path of the file and then add it in the declarations with the ngModule

import { StarComponent }  from './shared/star.component';


@NgModule({
  imports:      [ BrowserModule,FormsModule ],
  declarations: [ AppComponent , 
                  UserComponent,
                  ProductListComponent,
                  ProductFilterPipe,
                  StarComponent],
  bootstrap:    [ AppComponent ]
})



If a nested component wants to receive input from its container it must expose a property using @input decorator. This works with any property type.

The container component then passes it to the nested component with property binding. We enclose the binding target in [ ] bracket. We set the binding source to the data that the container wants to pass to the nested components

Note: The property has to be decorated with the input decorator
import  {Component, OnChanges , Input} from '@angular/core';
@Component({
selector:'ai-star',
templateUrl:'app/shared/star.component.html',
styleUrls:['app/shared/star.component.css']
})
export class StarComponent implements OnChanges {
  @Input() rating:number;
 startswidth:number;

 ngOnChanges(): void {
        this.starWidth = this.rating * 86 / 5;
    }
}
html
                <tbody>
                    <tr *ngFor='let product of products | productFilter:listFilter'>
                       <td><ai-star [rating]='products.starRating'></ai-star></td>
                    </tr>
                </tbody>


If the nested component want to send the information back to its container it can raise an event. The nested component exposes an event it can use to pass output to its container using output decorator

Output Decorator

Note:
  • The property type must be an event. 
  • The data to pass become an event payload

Steps explained

  • When the user clicks the star component receives that click event . 
  • We use the event binding in the star component binding to call the star component on click method
  • In the event click method we use the notify event property to call its emit method to raise the notify event to the container.
  • If we want to pass data then we pass it into the emit method
  • In the container template we use event binding to bid to this notify event

Nested Component

Container Component


No comments:

Post a Comment