Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Children component like in React's this.props.children in Angular 2?

Tags:

angular

How can I build a container component which can access child component like React's this.props.children?

like image 224
Kuan Avatar asked Nov 07 '16 23:11

Kuan


People also ask

How do you pass a prop to child component?

There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial. It's also important to note that React's props are read only (immutable). As a developer, you should never mutate props but only read them in your components.

How do you use props for kids?

By invoking them between the opening and closing tags of a JSX element, you can use React children for entering data into a component. The React children prop is an important concept for creating reusable components because it allows components to be constructed together.


2 Answers

in React you do

const Comp = ({ children }) => (
    <div class="wrapper">{children}</div>
);

in Angular2 you do

@Component({
    selector: 'comp',
    template: `
        <div class="wrapper"><ng-content></ng-content></div>
    `
})
class Comp {}
like image 92
jcperez-ch Avatar answered Oct 16 '22 23:10

jcperez-ch


You need to use @ViewChildren inside your component to access children placed inside the component.

Also, you want to decide where children are placed inside your template, you need to place an <ng-content></ng-content> somewhere in your template.

like image 22
Amit Avatar answered Oct 17 '22 01:10

Amit