Skip to content

Instantly share code, notes, and snippets.

@navix
Created February 11, 2019 12:10
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 navix/9b43582260f92b9e37aeb039970517df to your computer and use it in GitHub Desktop.
Save navix/9b43582260f92b9e37aeb039970517df to your computer and use it in GitHub Desktop.
Add nodes just after a component (not inside) in Angular 7

Add nodes just after a component (not inside) in Angular 7

For example we have radio-input and want to create a custom view. But no elements allowed inside input element.

<label>
  <input type="radio" uiRadio ...>
  Option A
</label>

ui-radio.component.html

<ng-template #checkTemplate>
  <label class="check" ...></label>
</ng-template>

ui-radio.component.ts

@Component({
  selector: 'input[type="radio"][uiRadio]',
  ...
})
export class UiRadioComponent ... {
  ...
  constructor(
    private vcr: ViewContainerRef,
    private elRef: ElementRef,
    ...
  ) {
  }
  
  ngAfterViewInit() {
    const viewRef = this.vcr.createEmbeddedView(this.checkTemplate);
    // ViewRef extends ChangeDetectionRef, needed for bindings update after projecting.
    viewRef['detectChanges']();
  }
}

Then you can style .check element as you want, it will be just after the input.


Implemented UiRadio in ngx-kit: https://github.com/ngx-kit/ngx-kit/tree/master/packages/collection/lib/ui-radio/ui-radio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment