What's the difference between using ng-content and using the childcomponent
selector inside the parent?
I can't really figure out when and why one or the other.
Examples:
//Parent
@Component({
selector: 'app-parent',
template: '<app-child [text]="'lorem ipsum'"></app-child>',
})
//Child
@Component({
selector: 'app-child',
template: '<p>{{text}}</p>',
})
// ... component class with "@Input() text"
versus
@Component({
selector: 'app-parent',
template: '<app-child>
<p>lorem ipsum</p>
</app-child>',
})
//Child
@Component({
selector: 'app-child',
template: '<ng-content></ng-content>',
})
CodePudding user response:
As you can see from your example, the content projection is a bit different from Input
.
With the ng-content
you are projecting your component from parent to child, and you can't work with that data on your child component.
Instead, with Input
the data is provided by the parent, but you can modify it in order to fit your UI and you should add a signature to the data that are incoming and work on it.
Es:
@Input() yourData: YourInterface | YourType
And with content projection (ng-content) this is not possible, because you can just draw the element from above and the child don't know what is. His logic will be: draw what receive, no matter what.