Skip to content

Instantly share code, notes, and snippets.

@phenomnomnominal
Last active January 29, 2019 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phenomnomnominal/211be8056bde09e4c36e333df6420780 to your computer and use it in GitHub Desktop.
Save phenomnomnominal/211be8056bde09e4c36e333df6420780 to your computer and use it in GitHub Desktop.
Content projection as inversion of control

Before:

class Car {
    private _engine: Engine;
    private _radio: Radio;
    
    constructor () {
        this._engine = new Engine();
        this._radio = new Radio();
    }
}

const car = new Car(); // can't swap out the engine or radio
@Component({
    selector: 'car',
    template: `
        <engine></engine>
        <radio></radio>
    `
})
class CarComponent { }

<car></car>

After:

class Car {
    constructor (
        private _engine: Engine,
        private _radio: Radio
    ) { }
}

const electricMotor = new ElectricMotor();
const sickRadio = new SickRadio();
const car = new Car(electricMotor, sickRadio); // Yay, extensible.
@Component({
    selector: 'car',
    template: `
        <ng-content select="engine"></ng-content>
        <ng-content select="radio"></ng-content>
    `
})
class CarComponent { }

<car>
  <engine></engine>
  <radio></radio>
</car>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment