【问题标题】:How to compile dynamic template in ng-content in angular 2如何在 Angular 2 中编译 ng-content 中的动态模板
【发布时间】:2017-06-30 14:20:49
【问题描述】:

我正在尝试通过编写自定义组件/指令来扩展/包装第三方(Angular Material 2)指令。

对于一个按钮,

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

我不会在我的应用程序的所有地方直接使用上述控件,而是将其包装在一个自定义组件中,我将在一个地方进行配置更改,它将影响使用自定义组件的所有其他地方。

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', '');    
  }
}

在 AfterViewInit 钩子中,我正在尝试设置元素属性“md-button”,我成功了,但我需要编译以获得材料外观和完整。如何编译 ng-content 中的模板。你能指导我吗?

【问题讨论】:

标签: angular angular2-template angular2-components angular2-compiler angular2-ngcontent


【解决方案1】:

Angular 在继承和组合方面非常有限。我相信在这种情况下包装MdButton 是一种更好的方法:

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


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

否则您将不得不提供原始模板、样式等...

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2020-05-23
    • 2018-03-30
    相关资源
    最近更新 更多