Angular perfect fowarding of component properties to a child component

时间:2017-08-04 12:01:32

标签: angular

I recently became aware of the following technique in React to foward properties to child components. This uses destructuring assignment:

const MyInputComponent = (props) => <input {...props} />

Using this you can perfectly wrap components without re-implementing their interface.

Is there a similar technique for Angular components?

Edit: found duplicate Angular2: passing ALL the attributes to the child component

1 个答案:

答案 0 :(得分:0)

I want to wrap an to add some html elements around it for styling and animation. Else I would have to repeat these elements many times.

ngcontent is your friend!

   @Component({
      selector: 'my-wrapper',
      template: `
        <h1>my fancy header</h1>
        <ng-content>YOUR INPUT WILL GO HERE</ng-content>

        `
    })

markup anywhere you want to use the wrapper:

    <div>
       <my-wrapper>
          <input .../>
       </my-wrapper>
   </div>

as you can see, the wrapper can have any template you want with any params you like. the inner html you put inside can have any markup you want with any params you like.