Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example #13

Open
ezzabuzaid opened this issue Aug 4, 2021 · 0 comments
Open

Example #13

ezzabuzaid opened this issue Aug 4, 2021 · 0 comments

Comments

@ezzabuzaid
Copy link
Owner

Time to try it out.

Here's a simple component that displays a color based on input and emits an event when it changes.

import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-color-box',
  template: `<div style="height: 250px; width: 250px;" [style.background-color]="backgroundColor"></div>`,
})
export class ColorBoxComponent implements OnChanges {
  @Input() backgroundColor: 'red' | 'blue' | 'green' = 'red';
  @Output() backgroundColorChanges = new EventEmitter<any>();
  
  ngOnChanges(changes: SimpleChanges): void {
    this.backgroundColorChanges.next(changes.backgroundColor);
  }
}

Host component declares <ng-template> with ColorBoxComponent as the dynamic-component with inputs and outputs.
Clicking on Change Color button will invoke ngOnChanges of ColorBoxComponent, just as it should be.

Try to change the input name and you'll see an exception thrown in the console.

import { Component } from '@angular/core';
import { ColorBoxComponent } from './color-box.component';

@Component({
  selector: 'app-root',
  template: `
  <ng-template
   [dynamic-component]="component"
   [inputs]="{backgroundColor: backgroundColor}"
   [outputs]="{backgroundColorChanges: onColorChange.bind(this)}">
  </ng-template>
  <button (click)="changeColor()">Change Color</button>
`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  component = ColorBoxComponent;
  backgroundColor: ColorBoxComponent['backgroundColor'] = 'green';

  onColorChange(value: ColorBoxComponent['backgroundColor']) {
    console.log(value, this.backgroundColor);
  }

  changeColor() {
    this.backgroundColor = 'blue';
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant