Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass props down in Angular 2+ like React?

In react I can arbitrarily pass props down like so:

function SomeComponent(props) {
  const {takeOutProp, ...restOfProps} = props;
  return <div {...restOfProps}/>;
}

How can I do the same thing in Angular?

--

More specifically, I want to write a custom dropdown component and pass props down to a select box.

like image 768
Rico Kahler Avatar asked Nov 14 '17 23:11

Rico Kahler


People also ask

How do you pass a prop in component Angular?

Answer: You can't. Props aren't a thing in Angular.

How do I pass a prop to a component?

To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax.

How do I pass JSX in props?

You want to use JSX inside your props You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.

Can we integrate React with Angular?

We can use create-react-app for creating main-app , sub-app for React and Angular CLI for creating sub-app in Angular.


2 Answers

As opposed to React components, Angular components aren't recompiled on input changes and use @Input property decorators to enable change detection. All properties that are expected to be passed should be explicitly defined as component inputs.

There are no better options than this one for custom select component. It's possible to read static attributes from current component element and set them on nested component element, but this won't set up bindings.

As for React recipe for deep props in wrapped components:

const Baz = props => <p>{props.baz}</p>;
const Bar = props => <Baz {...props} />;
const Foo = props => <Bar {...props} />;

This is usually handled by Angular DI and a hierarchy of injectors. A provider can be defined on respective injector in order to make data and behaviour available to nested components.

like image 76
Estus Flask Avatar answered Sep 29 '22 06:09

Estus Flask


Actually it is not the answer on your question but perhaps it helps you. You can add one custom directive with all params you need.

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[defaultConfig]'
})
export class DefaultDropdownConfigDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
       // your default config

    }
}

<my-dropdown defaultConfig></my-dropdown>

For more details you can read this

like image 38
Dmitry Grinko Avatar answered Sep 29 '22 08:09

Dmitry Grinko