nicholas
nicholas

Reputation: 14593

AngularJS app inside ReactJS component?

Is it possible to create an Angular app inside a react component?

Something like:

React.createClass({
    render: function() {
        return <div ng-app>...</div>;
    }
});

This is completely backwards, but will only have to be a temporary solution. I'm assuming I could do something like the code above, and add the angular bootstrapping to the componentDidMount lifecycle method.

Has anyone successfully done this?

Thanks.

Upvotes: 4

Views: 674

Answers (1)

Brigand
Brigand

Reputation: 86260

It would look something like this:

componentDidMount: function(){
    this._angularEl = document.createElement("div");
    this._angularEl.innerHTML = angularTemplatHTMLString;
    this._angularEl.setAttribute("ng-app", "");
    this.getDOMNode().appendChild(this._angularEl);
    // bind angular to this._angularEl
},
componentWillUnmount: function(){
    // unbind angular from this._angularEl

    this.getDOMNode().removeChild(this._angularEl);
    delete this._angularEl;
},
render: function(){
    return <div></div>
}

You could either use this for each component, or create a function which returns a mixin.

function makeAngularMixin(template){
    return { /* above code except for render */ }
}

or have a component which allows passing an angular template via props.

Upvotes: 4

Related Questions