如何创建新元素,从host元素绑定它们的事件,并用angular 6指令中的新元素替换host元素?

时间:2018-06-08 12:42:57

标签: html angular dom angular-directive

我有以下标记

<checkbox>
<div>
    <span (click)="toggle()">Text 1</span>
    <colorpicker>
    <span (click)="toggle()">Text 2</span>
    <input>
</div>

enter image description here

我正在使用角度6.复选框应在text1和text2点击上切换。并且所有控件都应该在一行中。第一个跨度太长,底部有空白区域,因此另一条线上有颜色选择。

enter image description here

我不能将复选框放在与text1相同的范围内,因为当用户点击colorpicker复选框时,切换不应该。我想将text1的所有单词划分为span。

enter image description here

我决定写一个derictive,但它不起作用。我想:

const text = el.innerHTML
const textInSpans = makeTextInSpan();
container.innerHTML = textInSpans;

容器和el.innerHTML中的问题,我编写了测试指令,但它不起作用

import { AfterViewInit, Directive, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
    selector: '[breakSpanOnWords]'
})
export class BreakSpanOnWordsDirective implements AfterViewInit {
    constructor(
        private viewContainerRef: ViewContainerRef,
        private templateRef: TemplateRef<any>
    ) { }

    public ngOnInit() {
        // this.viewContainerRef.createEmbeddedView(this.templateRef);
        this.templateRef.elementRef.nativeElement.innerHTML = '<span>test1</span><span></span2>';
        this.viewContainerRef.createEmbeddedView(this.templateRef);
    }
}

所以 1)如何获取应用指令的元素的内部html? 2)如何获取点击事件并将其绑定到新的跨度? 3)如何用其他元素替换这个元素?

0 个答案:

没有答案
相关问题