Angular中的DOM操作

Angular可以运行在不同的平台上--浏览器,移动平台或web worker。因此,站在平台特定的API和框架接口之间需要抽象层次。在Angular中,这些抽象成为以下引用类型的形式:ElementRef,TemplateRef,ViewRef,ComponentRef和ViewContainerRef。在本文中,我们将详细介绍每种引用类型,并展示如何使用它们来操作DOM

@ViewChild

Angular提供 @ViewChild和@ViewChildren装饰器来进行DOM查询。他们的行为是一样的,只是前者返回一个reference,后者返回一个QueryList对象,该对象包含多个reference

通常,这些装饰器与模板引用变量配对使用。模板引用变量只是对模板中的DOM元素的命名引用。您可以将其视为与html元素的id属性类似的东西。用模板引用标记DOM元素,然后使用ViewChild装饰器在类中查询它。这里是基本的例子:

@Component({
    selector: 'sample',
    template: `
        <span #tref>I am span</span>
    `
})
export class SampleComponent implements AfterViewInit {
    @ViewChild("tref", {read: ElementRef}) tref: ElementRef;

    /** AfterViewInit之后@ViewChild才生效 */
    ngAfterViewInit(): void {
        // outputs `I am span`
        console.log(this.tref.nativeElement.textContent);
    }
}

ViewChild装饰器的基本语法如下:
@ViewChild([reference from template], {read: [reference type]});

在这个例子中,你可以看到我在html中指定了tref作为模板引用名,并且得到与这个元素相关的ElementRef。第二个参数并不是必需的,因为Angular可以通过DOM元素的类型来推断引用类型。例如,如果它是一个简单的HTML元素(如span),那么angular将返回ElementRef。如果它是一个模板元素,它将返回TemplateRef。但是有一些引用,如ViewContainerRef不能被推断,并且必须read参数中指。还有其他的,比如ViewRef不能从DOM返回,必须手动构造。

ElementRef

这是最基本的抽象。如果你观察它的类结构,你会发现它只保存了它所关联的native element。对于访问native DOM element非常有用,如下:

// outputs `I am span`
console.log(this.tref.nativeElement.textContent);

不过,Angular团队不鼓励这种用法。这不仅会带来安全风险,还会在应用程序和渲染层之间造成紧密耦合,这使得在多个平台上运行应用程序变得困难。这种凡是破坏了抽象。后面你会看到,在Angular中实现的DOM操作中几乎不需要这样一个较低级别的访问。

可以使用@ViewChild为任何DOM元素返回ElementRef。但是,由于所有components都包含在在自定义DOM元素中,并且所有directive都依附于DOM元素,因此组件和指令类可以通过DI机制获取与其主机元素关联的ElementRef实例:

@Component({
    selector: 'sample',
    ...
export class SampleComponent{
    constructor(private hostElement: ElementRef) {
        //outputs <sample>...</sample>
        console.log(this.hostElement.nativeElement.outerHTML);
    }

TemplateRef

模板的概念应该是大多数Web开发人员熟悉的。在整个应用程序的视图中重复使用一组DOM元素。在HTML5标准引入了template标签之前,大多数都是用下面这种方式实现,增加type属性:

<script>
    let tpl = document.querySelector('#tpl');
    let container = document.querySelector('.insert-after-me');
    insertAfter(container, tpl.content);
</script>
<div class="insert-after-me"></div>
<ng-template id="tpl">
    <span>I am span in template</span>
</ng-template>

Angular支持这种方法,并实现TemplateRef类来处理模板。以下是如何使用它:

@Component({
    selector: 'sample',
    template: `
        <ng-template #tpl>
            <span>I am span in template</span>
        </ng-template>
    `
})
export class SampleComponent implements AfterViewInit {
    @ViewChild("tpl") tpl: TemplateRef<any>;

    ngAfterViewInit() {
        let elementRef = this.tpl.elementRef;
        // outputs `template bindings={}`
        console.log(elementRef.nativeElement.textContent);
    }
}

Angular从DOM中删除模板元素,并在其位置插入注释。这是呈现时的样子:

<sample>
    <!--template bindings={}-->
</sample>

TemplateRef类本身就是一个简单的类。It holds a reference to its host element in elementRef property and has one method createEmbeddedView。这个方法是非常有用的,因为它允许我们创建一个视图并以ViewRef的形式返回一个引用

ViewRef

Angular鼓励开发人员将UI视为Views的组合,而不是将其视为独立的HTML标记树。

Angular支持2种视图

  • Embedded Views which are linked to a Template
  • Host Views which are linked to a Component

Creating embedded view

ngAfterViewInit() {
    let view = this.tpl.createEmbeddedView(null);
}

Creating host view

constructor(private injector: Injector,
            private r: ComponentFactoryResolver) {
    let factory = this.r.resolveComponentFactory(ColorComponent);
    let componentRef = factory.create(injector);
    let view = componentRef.hostView;
}

ViewContainerRef

表示可以附加一个或多个视图的容器。

首先要提到的是,任何DOM元素都可以用作视图容器。通常,ViewContainerng-container结合使用。ng-container会被渲染为一个注释,所以它不会在DOM中引入多余的html元素。以下是在组件模板的特定位置创建ViewContainer的示例:

@Component({
    selector: 'sample',
    template: `
        <span>I am first span</span>
        <ng-container #vc></ng-container>
        <span>I am last span</span>
    `
})
export class SampleComponent implements AfterViewInit {
    @ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;

    ngAfterViewInit(): void {
        // outputs `template bindings={}`
        console.log(this.vc.element.nativeElement.textContent);
    }
}

Manipulating views

ViewContainer为操作视图提供了一个方便的API

class ViewContainerRef {
    ...
    clear() : void
    insert(viewRef: ViewRef, index?: number) : ViewRef
    get(index: number) : ViewRef
    indexOf(viewRef: ViewRef) : number
    detach(index?: number) : ViewRef
    move(viewRef: ViewRef, currentIndex: number) : ViewRef
}

我们之前已经看到,如何从模板和组件手动创建两种类型的视图。一旦我们有了一个视图,我们可以使用插入方法将其插入到DOM中。所以,下面是从模板中创建一个嵌入式视图并将其插入到由ng-container元素标记的特定位置的示例:

@Component({
    selector: 'sample',
    template: `
        <span>I am first span</span>
        <ng-container #vc></ng-container>
        <span>I am last span</span>
        <ng-template #tpl>
            <span>I am span in template</span>
        </ng-template>
    `
})
export class SampleComponent implements AfterViewInit {
    @ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;
    @ViewChild("tpl") tpl: TemplateRef<any>;

    ngAfterViewInit() {
        let view = this.tpl.createEmbeddedView(null);
        this.vc.insert(view);
    }
}

Creating Views

ViewContainer还提供API来自动创建视图:

class ViewContainerRef {
    element: ElementRef
    length: number

    createComponent(componentFactory...): ComponentRef<C>
    createEmbeddedView(templateRef...): EmbeddedViewRef<C>
    ...
}

这些都是我们上面手动完成的简单包装。他们从模板或组件创建一个视图,并将其插入到指定位置。

ngTemplateOutlet and ngComponentOutlet

上面介绍了底层机制,但是Angular提供了2个指令: ngTemplateOutletngComponentOutlet,只需在html(template)中快速实现创建视图

ngTemplateOutlet

@Component({
    selector: 'sample',
    template: `
        <span>I am first span</span>
        <ng-container [ngTemplateOutlet]="tpl"></ng-container>
        <span>I am last span</span>
        <ng-template #tpl>
            <span>I am span in template</span>
        </ng-template>
    `
})
export class SampleComponent {}

ngComponentOutlet

<ng-container *ngComponentOutlet="ColorComponent"></ng-container>

demo
原文地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容