• 最佳实践与填坑的积累
    • 1. 删除由Angular组件创建的Host HTML元素选择器
    • 2.判断<ng-content>为空

    最佳实践与填坑的积累

    1. 删除由Angular组件创建的Host HTML元素选择器

    写一个remove-host 指令

    1. //remove the host of avatar to be rendered as svg
    2. @Directive({
    3. selector: '[remove-host]'
    4. })
    5. class RemoveHost {
    6. constructor(private el: ElementRef) {
    7. }
    8. //wait for the component to render completely
    9. ngOnInit() {
    10. var nativeElement: HTMLElement = this.el.nativeElement,
    11. parentElement: HTMLElement = nativeElement.parentElement;
    12. // move all children out of the element
    13. while (nativeElement.firstChild) {
    14. parentElement.insertBefore(nativeElement.firstChild, nativeElement);
    15. }
    16. // remove the empty element(the host)
    17. parentElement.removeChild(nativeElement);
    18. }
    19. }

    使用方式:
    <avatar [name]="hero.name" remove-host></avatar>

    来自stackoverflow

    2.判断<ng-content>为空

    Wrap ng-content in an HTML element like a div to get a local reference to it, then bind the ngIfexpression to ref.childNodes.length == 0:

    1. template: `<div #ref><ng-content></ng-content></div>
    2. <span *ngIf="ref.childNodes.length == 0">
    3. Display this if ng-content is empty!
    4. </span>`

    来自stackoverflow