简体   繁体   中英

How to compile dynamic template in ng-content in angular 2

I am trying to extend/wrap a third party(Angular Material 2) directive by writing a custom component/directive.

For a button,

<button type="button" md-button>Some Text</button>

Instead of using above control directly at all places in my application, i will wrap it inside one custom component and i will do configuration changes at one place and it will affect all other places where ever the custom component is used.

import { MdButton } from '@angular/material';
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  OnInit,
  Renderer,
  ViewChild,
  ViewEncapsulation
} from '@angular/core';

@Component({
  selector: '[at-button]',
  template: `<ng-content></ng-content>`,
  styleUrls: []
})
export class AtButtonComponent extends MdButton implements OnInit, AfterViewInit {
  // @ViewChild(MdButton)
  // private mdButton:MdButton
  private eleRef: ElementRef;
  private renderRef: Renderer;

  constructor(_renderer: Renderer, _elementRef: ElementRef) {
    super(_elementRef, _renderer);

    this.eleRef = _elementRef;
    this.renderRef = _renderer;
  }

  ngOnInit() {
  }

  ngAfterViewInit(): void {

    this.disableRipple = true;
    this.color = 'warn';
    this.renderRef.setElementAttribute(this.eleRef.nativeElement, 'md-button', '');    
  }
}

Here in AfterViewInit hook , i am trying to set element attribute 'md-button', i was successful in that but i need compile to get the material look and full. How to compile the template which resides in ng-content. Can you guide me.

Angular is quite limited when it comes to inheritance and composition. I believe that in this case wrapping MdButton is a better way:

@Component({
  selector: '[at-button]',
  template: `<button type="button" md-button><ng-content></ng-content></button>`,
  styleUrls: []
})


<div at-button>Click Me</div>

Otherwise you will have to supply original template, styles, etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM